如何在括号之间输入值并在JAVA中打印出这些值

时间:2015-11-03 22:57:03

标签: java printing

我正在制作一个程序,人们可以从菜单中选择菜肴,并可以选择他们想要订购的菜肴的数量。我使用以下代码:

    Scanner input = new Scanner(System.in);

    String [] starterList = {"Gazpacho with shrimps", "Carpaccio of veal    ", "Mushroom salad with nuts (v)"};

    System.out.println("Please choose what dishes you want to order");
    System.out.println("");
    System.out.println("-- STARTERS --");

    for (int i = 0; i < starterList.length; i++){
        System.out.println((i+1) + ". " + starterList[i] + "\t" + "[ ]");
    }
    System.out.println("");
    System.out.println("Choose how many you want of each:");   

这个想法是,在每个菜肴后面,用户可以填写他们想要在[]之间订购的金额,在他们填写金额之后,我应该能够打印概述订单的确切内容。这是我被卡住的地方。所以我想知道a)甚至可以在括号之间输入值吗?和b)我该怎么做?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

控制台输入不允许这样做,但您可以尝试以下代码

\\code starts

import java.util.Scanner;

公共类订单{

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String[] starterList = {"Gazpacho with shrimps", "Carpaccio of veal    ", "Mushroom salad with nuts (v)"};
    int[] quantity = new int[starterList.length];

    System.out.println("Please choose what dishes you want to order");
    System.out.println("");
    System.out.println("-- STARTERS --");

    for (int i = 0; i < starterList.length; i++) {
        System.out.println((i + 1) + ". " + starterList[i] + "\t" + "[ ]");
    }
    System.out.println("");
    System.out.println("Choose how many you want of each:");
    System.out.println("Enter 0 if you do not want to order the dish:");

    for (int i = 0; i < starterList.length; i++) {
        System.out.print((i + 1) + ". " + starterList[i] + "\t");
        quantity[i] = input.nextInt();
    }
    System.out.println("");
    System.out.println("Your final order is:");
    int index=1;
    for (int i = 0; i < starterList.length; i++) {
        if (quantity[i] != 0) {
            System.out.println((index++) + ". " + starterList[i] + "\t" + "[ " + quantity[i] + " ]");
        }
    }

}

} \代码结束

enter image description here

这应该有这样的效果

请选择您要订购的菜肴

- STARTERS - 1.西班牙凉菜汤虾仁[] 2.小​​牛肉的卡帕西欧[] 3.带坚果的蘑菇沙拉(v)[]

选择每个人的数量: 如果您不想订购菜,请输入0: 1.西班牙凉菜汤虾仁2 2.小​​牛肉的生牛肉片0 3.带坚果的蘑菇沙拉(v)3

您的最终订单是: 1.西班牙凉菜汤虾仁[2] 2.带坚果的蘑菇沙拉(v)[3]

此处第二项的订单为0,因此它不在所选项目列表中。