2015-02-11 56 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("[ ]+"); 

然后通过检查零件的尺寸和循环。