2015-02-11 24 views
-1

所以我應該收集用戶輸入的數據爲遊戲在Java中使用變量與parseInt函數

int[] player1 = new int[4]; 
      try { 
       player1[4] = Integer.parseInt(keyin.nextLine()); 
      } 
      catch(NumberFormatException e) { 
       System.out.println("Player 2 : "); } 

在try-catch是跳到下一個播放器時PLAYER1按下Enter鍵,但我的問題得到的是我似乎無法找到一種方法來使用player1輸入的變量。我需要這些值與另一個比較,但使用int player1[0]不起作用。

我在哪裏可以找到該人員輸入的值?

程序運行的一個例子:

Player 1: 12 1 5 // these numbers are user inputted 
Player 2: 12 4 3 
[...] 
+0

您需要一個循環。 – 2015-02-11 22:27:20

+4

player1 [4]將拋出IndexOutOfBoundsException。 – alterfox 2015-02-11 22:28:23

+0

@alterfox它的確如此!有時候......我似乎無法使這項工作正常進行,有什麼建議嗎? – X1XX 2015-02-11 22:31:38

回答

1

您需要設置一個循環都在輸入讀,以及到顯示那些輸入。

您的下列代碼無法運行;您正在嘗試訪問超出數組範圍的數據。

player1[4] = Integer.parseInt(keyin.nextLine()); 

如果聲明您陣列像這樣:int[] player1 = new int[4]; 那麼你有以下指標的使用方法:

| 0 | 1 | 2 | 3 |` //This gives you 4 indexes! But player1[3] is the last usable index 

請記住,當你試圖訪問編程數組的元素或任何元素,電腦開始編號爲零!任何嘗試訪問超出此數據的嘗試都可能導致意外行爲,導致程序突然終止。

我建議你檢查以下資源:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
http://www.tutorialspoint.com/java/java_loop_control.htm

http://www.programmingsimplified.com/java/tutorial/java-while-loop 

Scanner input = new Scanner(System.in); 
System.out.println("Input an integer"); 

while ((n = input.nextInt()) != 0) { 
    System.out.println("You entered " + n); 
    System.out.println("Input an integer"); 
} 

System.out.println("Out of loop"); 

}

+0

所以我改成'對(INT I = 0; I <5; i ++在){ \t \t \t \t \t PLAYER1 [I] =的Integer.parseInt(keyin.nextLine());} \t \t \t} \t \t \t catch(NumberFormatException e){ \t \t \t System.out.println(「Player 2:」); }'但它仍然不適用於其他任何事情,除了第一個整數 – X1XX 2015-02-12 00:10:45

+0

@PatrickBui你仍然有1-over錯誤。您的索引不會達到4.它只會達到3.請參閱上面的示例。如果你嘗試訪問player1 [4],這將不起作用。該位置沒有有效的數據。您最後可訪問的索引是3。 請看看上面更新的例子 – 2015-02-12 00:49:41

+0

對不起,我忘了寫我改變'int [] player1 = new int [4]'爲'int [] player1 = new int [5]'!! – X1XX 2015-02-12 00:56:07

0
String string = keyin.nextLine(); 
String[] parts = string.split("[ ]+"); 

然後通過檢查零件的尺寸和循環。