我想将扫描仪的输入放入我的数组中,但收到错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
我的代码:
public static void main(String[] args)
{
Scanner scanInput = new Scanner(System.in);
Random randomGen = new Random();
String captureString[] = new String[] {};
System.out.println("Please enter some words..");
captureString[0] = scanInput.next();
captureString[1] = scanInput.next();
captureString[2] = scanInput.next();
System.out.println("You entered: " + captureString[0] + " " + captureString[1] + " " + captureString[2]);
}
}
我无法使用循环或条件(任务),那么数组是否可行?或者我应该只使用变量,我想使用数组的唯一原因是因为我想在之后进行一些字符串操作,这对于变量来说可能有点尴尬
最佳答案
既然你得到了三个输入,我建议。将其更改为String captureString[] = new String[3];
。这是因为,数组在使用之前需要进行初始化。因为您没有初始化任何值。其中不会有任何索引。因此,当您访问索引 0
时,您将收到 ArrayIndexOutOfBoundsException
。希望它能澄清!
关于Java 扫描器输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419460/