while循环在输入值之前首先打印双精度

在询问切换器的输入之前,字符串 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;


慕沐林林
浏览 99回答 1
1回答

慕无忌1623718

这是因为您使用 sc.nextInt() 来获取用户的输入,并且它不会消耗该行,因此当您使用 switcher = sc.nextLine(); 时&nbsp;它仍然读取用户之前输入的号码。您可以在 catcher = sc.nextInt(); 之后添加此内容&nbsp;消耗该行:&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(sc.hasNextLine()){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sc.nextLine(); &nbsp;&nbsp;&nbsp;&nbsp;}或者您也可以使用:catcher&nbsp;=&nbsp;Integer.parseInt(sc.nextLine());将用户输入转换为整数值也将起作用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java