在詢問切換器的輸入之前,字符串 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
提交
取消