4 回答

TA貢獻1872條經驗 獲得超4個贊
你聲明了兩次。將第二個聲明更改為僅分配給它,您應該沒問題:confirm
confirm = userInput.next().charAt(0); // No datatype, so you aren't declaring confirm, just assigning to it

TA貢獻1817條經驗 獲得超6個贊
似乎除了重新聲明變量之外,還有一個或多個問題 -confirm
問題 1:
后。它不會提示輸入國家/地區,而是提示 。int age = userInput.nextInt()
Press Y to continue or N to start over
此問題的原因:
由于您使用的是掃描儀,因此只會從輸入中獲取整數值,并且將跳過換行符。int age = userInput.nextInt();
\n
修復
作為解決方法,我在之后添加了這樣,它將在之后消耗字符。userInput.nextLine();
int age = userInput.nextInt();
\n
nextInt()
問題 2:
在第 1 次迭代后,此行將導致問題。confirm = userInput.next().charAt(0);
此問題的原因:
在第 2 次迭代中,您不會收到輸入名稱的提示,因為該行將采用上次迭代作為輸入,并將跳過并提示 age 。String name = userInput.nextLine();
\n
How old are you?
修復
作為一種解決方法,我在之后添加了這樣一個,它將在之后使用字符,并且下一次迭代將按預期進行。userInput.nextLine();
confirm = userInput.next().charAt(0);
\n
userInput.next().charAt(0)
問題 3:
這個邏輯只期望和在,但在這里你是期望和兩者。if (confirm !='y' || confirm !='n')
y
n
lowercase
while(confirm == 'Y'|| confirm == 'y')
y
Y
修復 - 我已經在下面的代碼中添加了必要的更改,但建議您將其更改為開關盒。
注意:
不建議在每次輸入后都這樣做,您可以簡單地解析它。有關詳細信息,請參閱此處。
userInput.nextLine()
我不推薦它,但這會讓你的程序工作
Scanner userInput = new Scanner(System.in);
char confirm;
do {
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
userInput.nextLine(); //adding this to retrieve the \n from nextint()
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is " + name + ", you are " + age
+ "years old and you would like to visit " + country + " ?");
System.out.println("Press Y to continue or N to start over");
confirm = userInput.next().charAt(0);
userInput.nextLine(); //adding this to retrieve the \n this will help in next iteration
System.out.println(name + " landed in " + country + " at the age of " + age + ".");
if (confirm == 'y' || confirm == 'Y') {
continue; // keep executing, won't break the loop
} else if (confirm == 'n' || confirm == 'N') {
break; // breaks the loop and program exits.
} else {
System.out.println("Sorry that input is not valid, please try again");
// the program will exit
}
} while (confirm == 'Y' || confirm == 'y');
}
建議您使用 switch case 而不是 if 比較并解析字符和整數輸入并刪除任意添加作為解決方法。confirmationuserInput.nextLine()

TA貢獻1853條經驗 獲得超9個贊
修復的另一個選項是刪除不必要的聲明char confirm;
并僅在需要時使用
char confirm = userInput.next().charAt(0);
根據@ScaryWombat建議,您需要更改變量的作用域(當前作用域與while
do
)
添加回答
舉報