好的,我把数字列表作为输入作为字符串,我想取这些数字并用它们创建一个int数组。
import java.util.Scanner;
public class StringSplit
{
public static void main(String[] args)
{
int a;
int i = 0;
String s;
Scanner input = new Scanner(System.in);
System.out.println("This programs simulates a queue of customers at registers.");
System.out.println("Enter the number of registers you want to simulate:");
a = input.nextInt();
while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");
a = input.nextInt();
}
System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.
Enter: ");
s = input.next();
String[] parts = s.split(" ");
System.out.println(parts[1]);
for(int n = 0; n < parts.length; n++) {
System.out.println(parts[n]);
}
input.close();
}
}
如果我能够创建整个阵列,那么一切都会很棒但是出于某种原因我得到了这个:
Input:
0 0 1 1 2 2
Output:
0
多数民众赞成。只打印数组的第一个元素。我应该尝试手动打印和零件[1]等元素(就像我一样,我得到这个:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at QueueSimulation.main(QueueSimulation.java:32)
为什么会这样?更重要的是我如何解决它?