在Java中使用parseInt变量

在Java中使用parseInt变量,java,Java,所以我应该从游戏的用户输入中收集数据 int[] player1 = new int[4]; try { player1[4] = Integer.parseInt(keyin.nextLine()); } catch(NumberFormatException e) { System.out.println("Player 2 : "); } try catch是在

所以我应该从游戏的用户输入中收集数据

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
[...]

您需要设置一个循环来读取输入和显示这些输入

下面的代码不起作用您正在尝试访问超出数组边界的数据

player1[4] = Integer.parseInt(keyin.nextLine());
如果您这样声明数组:
int[]player1=newint[4]
然后您可以使用以下索引:

| 0 | 1 | 2 | 3 |` //This gives you 4 indexes! But player1[3] is the last usable index
请记住,当您试图访问数组元素或编程中的任何元素时,计算机开始在零处编号超出此范围的任何访问数据的尝试都可能导致意外行为,导致程序突然终止。

我鼓励您检查以下资源:

}


然后检查零件的大小并循环。

player1[4]将抛出一个IndexOutOfBoundsException。@alterfox确实如此!有时。。。我似乎无法使它正常工作,有什么建议吗?是的,阅读有关数组的内容。这是基本的东西!所以我把它改为
for(inti=0;i@PatrickBui您仍然存在1-over错误。您的索引没有变为4。它只变为3。请参见上面的示例。如果您尝试访问player1[4],这将不起作用。该位置没有有效数据。您最后可访问的索引是3。请参阅上面更新的示例抱歉,我忘了写我将
int[]player1=new int[4]
更改为
int[]player1=new int[5]
!!@PatrickBui尝试使用上面新添加的代码段,这应该会有所帮助
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");
String string = keyin.nextLine();
String[] parts = string.split("[ ]+");