在询问切换器的输入之前,字符串 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 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
这是因为您使用 sc.nextInt() 来获取用户的输入,并且它不会消耗该行,因此当您使用 switcher = sc.nextLine(); 时 它仍然读取用户之前输入的号码。
您可以在 catcher = sc.nextInt(); 之后添加此内容 消耗该行:
if (sc.hasNextLine()){ sc.nextLine(); }
或者您也可以使用:
catcher = Integer.parseInt(sc.nextLine());
将用户输入转换为整数值也将起作用。
添加回答
举报
0/150
提交
取消