1 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
nextInt()行為類似于next()當(dāng)它讀取一行時(shí),它將光標(biāo)放在該行后面。
示例:您輸入 6
6
^(scanner's cursor)
所以下次你打電話的時(shí)候nextLine()。它將返回光標(biāo)之后的整行,在本例中光標(biāo)為空。
要解決此問題,您需要調(diào)用一個(gè)額外函數(shù),nextLine()以便掃描儀關(guān)閉它正在讀取的上一行并轉(zhuǎn)到下一行。
你可以這樣做
System.out.print("Please enter a choice: ");
choice = scan.nextInt(); // Reads the int
scan.nextLine(); // Discards the line
在選擇 2 中,由于您想要用戶的全名,因此您可以使用它nextLine()來獲取整行和空格。
//Remove user
System.out.println("Please enter full name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
或者您可以執(zhí)行與選項(xiàng) 1 中類似的操作
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
key = lastName.concat(firstName);
System.out.println("name:" + key);
ad1.removeContact(key);
scan.nextLine(); // This is will make sure that in you next loop `nextInt()` won't give an input mismatch exception
添加回答
舉報(bào)