我知道這段代碼是非常可寫的(Java和編程的第一天),但是我正在用Java編寫代碼,它將從用戶(骰子)獲取輸入並從該骰子產生一個隨機數。我添加了一個while循環來詢問用戶是否想要重新啓動程序,但每次運行它時,都會告訴我在輸入任何內容之前它是無效的輸入。請幫忙。爲什麼我的Java代碼不工作?
import java.util.Scanner;
import java.util.Random;
public class Java {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String restartChoice = "y";
while (restartChoice == "y" || restartChoice == "Y"){
int choice;
System.out.println("Please choose which dice you would like to roll. 4/6/12 ");
choice = input.nextInt();
while (choice != 4 && choice != 6 && choice != 12){
System.out.println("That is not a valid input, please try again... ");
choice = input.nextInt();
}
Random rand = new Random();
int value = rand.nextInt(choice) + 1;
System.out.print("You chose to roll the ");
System.out.print(choice);
System.out.print(" sided dice. The number is ");
System.out.println(value);
System.out.println("Would you like to restart? Y/N ");
restartChoice = input.nextLine();
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
}
}
}
請參閱[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – iamnotmaynard
@原始海報,適合初學者,除了Reimeus指出的錯誤之外,你的代碼一點都不差,因此我不同意這個說法:''我知道這段代碼是非常可寫的(Java和編程的第一天)......「 ' –
@project_legacy此外,請注意第一個['Scanner#readLine()'](http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextLine() )調用 - 檢查文檔,但我認爲'restartChoice'將是空的,所以這就是爲什麼你看到'這不是一個有效的輸入...'。 – Jonathan