2012-10-03 27 views
0

我有一系列的骰子和每一個,我需要提醒用戶,如果他們想重播它或不。最簡單的方法似乎是Scanner類的提示 - 我檢查它們輸入的內容並正確處理。但是,如果請求的數據不存在於用戶輸入中,scanner.next()將引發異常。所以,scanner.hasnext()需要以某種方式適應這裏。如何使用Scanner.hasNext填充多個數組值?

這是我的代碼;它會進入條目進入響應數組,但如果用戶輸入既不包含Ÿ也不N.將拋出一個異常

public Boolean[] chooseDice(int diceNum){ 
    Boolean[] responses = new Boolean[diceNum]; 
    Scanner scansworth = new Scanner(System.in); 
    for (int i=0; i<diceNum; i++){ 
     System.out.printf("Reroll this die? (%d)\n",i); 
       responses[i] = (scansworth.next("[YN]")) == "Y" ? true : false; 
    } 
     return responses; 

如何調用scansworth.hasNext(「[YN]」),從而使intepreter沒有按鎖定並且在循環的每一步之後都能正確檢查輸入?

+0

'系統忽略一些循環的一部分 - >這個語句實際上是什麼意思? –

+0

如果我嘗試在循環內部等待hasNext成爲true,它會在第一次正確運行,然後下一次不會正確啓動。 (我已經嘗試了幾種不同的變化,沒有在我面前發生日食,所以很難精確解釋。) – argentage

+0

我編輯了這篇文章,試圖讓它更加明顯。 – argentage

回答

1

可以圍繞碼讀取用戶輸入了一段時間,以檢查用戶輸入是否是在給定的模式....使用hasNext("[YN]") ..還有,你不需要scanner.next([YN]) ..只要使用next() ..這將獲取你的下一行輸入,你可以用「Y」進行比較..

for (int i=0; i<diceNum; i++){ 
      int count = 0; 
      System.out.printf("Reroll this die? (%d)\n",i); 

      // Give three chances to user for correct input.. 
      // Else fill this array element with false value.. 

      while (count < 3 && !scansworth.hasNext("[YN]")) { 
       count += 1; // IF you don't want to get into an infinite loop 
       scansworth.next(); 
      }  

      if (count != 3) { 
       /** User has entered valid input.. check it for Y, or N **/ 
       responses[i] = (scansworth.next()).equals("Y") ? true : false; 
      } 
      // If User hasn't entered valid input.. then it will not go in the if 
      // then this element will have default value `false` for boolean.. 
} 
+0

你爲什麼要檢查計數<3?爲什麼特別是3?它應該不是diceNum? – KG2289

+0

我只是檢查它,所以如果hasNext()是假的,它不會進入無限循環..它給3個機會獲得一個數組元素的輸入..它是爲每個輸入.. –

+0

@airza ..現在我認爲這段代碼將完全按照你想要的方式做。 –

0

我想你可以嘗試這樣的事情.....

public Boolean[] chooseDice(int diceNum){ 
    Boolean[] responses = new Boolean[diceNum]; 
    boolean isCorrect = false; 
    Scanner scansworth = new Scanner(System.in); 
    for (int i=0; i<diceNum; i++){ 

while(!isCorrect){ 

if((scansworth.hasNext().equalsIgnoreCase("Y")) || (scansworth.hasNext().equalsIgnoreCase("N")))`{ 



    responses[i] = scansworth.next(); 
    isCorrect = true; 

}else{ 

     isCorrect = false; 


    } 
    } 

}