2013-06-23 42 views
1

我知道這段代碼是非常可寫的(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(); 
     } 
    } 
} 

}

+0

請參閱[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – iamnotmaynard

+0

@原始海報,適合初學者,除了Reimeus指出的錯誤之外,你的代碼一點都不差,因此我不同意這個說法:''我知道這段代碼是非常可寫的(Java和編程的第一天)......「 ' –

+0

@project_legacy此外,請注意第一個['Scanner#readLine()'](http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextLine() )調用 - 檢查文檔,但我認爲'restartChoice'將是空的,所以這就是爲什麼你看到'這不是一個有效的輸入...'。 – Jonathan

回答

0

Scanner#nextInt()不消耗造成的字符換行字符傳遞通過對循環

while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){ 
      System.out.println("That is not a valid input. Please try again. "); 
      restartChoice = input.nextLine(); 
} 

添加nextLine聲明每次nextLine語句之後消耗這個換行符。

choice = input.nextInt(); 
input.nextLine(); 

另外==運算符比較對象引用。使用String#equals

while (restartChoice.equals("y") || restartChoice.equals("Y")) { 

,以防止NullPointerException您可以將String字面第一。也equalsIgnoreCase可以用來給一個較短的if語句表達:

while ("y".equalsIgnoreCase(restartChoice)) { 

這種變化是在while語句表達所需要的。

+0

謝謝你的回答,但我仍然很困惑。即使在將字符串作爲對象進行比較之後,仍會打印輸入不正確(重新啓動選項不是「Y」或「N」,即使尚未輸入任何內容) –

+0

這是由於'Scanner#nextInt'不要使用換行符。查看更新 – Reimeus

+0

非常感謝,我已經讓我的程序現在可以工作了。 –

0

使用String.equals(otherString)

字符串是對象,而不是基元。您目前正在比較字符串的地址。