在输入值之前,while循环首先打印两次

时间:2019-09-09 15:03:31

标签: java stack

在要求输入切换器之前,String asd会打印两倍,现在我感到绝望了。我希望字符串“ asd”仅打印一次,但在我的情况下打印两次,我的猜测是一个错误或循环,对不起,我在这里很陌生,正在编程中

public class FruitBasket {

static String option;
static String choice1;
static int catcher;
static int counter1 = 1;
static int counter = 0;
static String eater = "e";
static Scanner sc = new Scanner(System.in);       
static Stack<String> basket = new Stack();
static String switcher;

public static void main(String[] args) {

    catching();

}

static void catching(){

    System.out.println("Catch and eat any of these fruits: " + "'apple', 'orange', 'mango', 'guava'" );
    System.out.println("A apple, O orange, M mango, G guava");
    System.out.print("How many fruits would you like to catch? ");
    catcher = sc.nextInt();

    switches();
     }

     static void switches(){

    while(counter1 < catcher)  {
    String asd = "Fruit " + counter1 + " of " + catcher + ":";
    System.out.print(asd);

    switcher = sc.nextLine();
         switch (switcher) {
            case "a":
                basket.push("apple");
                counter++;
                counter1++;
                break;

1 个答案:

答案 0 :(得分:0)

这是因为您正在使用sc.nextInt()从用户那里获取输入,并且它不会占用该行,所以当您使用switcher = sc.nextLine();仍然会读取用户之前输入的号码。

您可以在catcher = sc.nextInt();之后添加它。消耗该行:

    if (sc.hasNextLine()){
        sc.nextLine();
    }

或者您可以使用:

catcher = Integer.parseInt(sc.nextLine());

要将用户输入转换为整数值,它也将起作用。