“线程中的异常”;“主要”;获取未知数量的输入,然后获取另一个输入时发生java.util.NoSuchElementException
我最初使用“线程中的异常”;“主要”;获取未知数量的输入,然后获取另一个输入时发生java.util.NoSuchElementException,java,arrays,java.util.scanner,nosuchelementexception,Java,Arrays,Java.util.scanner,Nosuchelementexception,我最初使用hasNext()在数组中获取未知数量的输入,然后获取另一组输入,但获取NoSuchElementException 代码段: public class Hello { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] array = new int[100]; int input = 0; wh
hasNext()
在数组中获取未知数量的输入,然后获取另一组输入,但获取NoSuchElementException
代码段:
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = new int[100];
int input = 0;
while (sc.hasNext()) {
array[input++] = sc.nextInt();
}
int k = sc.nextInt();
int[] newArray = new int[100];
int j = 0;
for (int h = 0; h < k; h++)
newArray[j++] = sc.nextInt();
}
}
公共类你好{
公共静态void main(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
int[]数组=新的int[100];
int输入=0;
while(sc.hasNext()){
数组[input++]=sc.nextInt();
}
int k=sc.nextInt();
int[]newArray=newint[100];
int j=0;
对于(int h=0;h
读取所有值,然后调用int k=sc.nextInt();再一次。这就是例外的原因。尝试添加一些逻辑,以更确定的方式获取所有输入。
从源头
/**
* Scans the next token of the input as an <tt>int</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextInt()</tt> behaves in exactly the same way as the
* invocation <tt>nextInt(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>int</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt() {
return nextInt(defaultRadix);
}
这回答了你的问题吗?在while循环之后转储/调试sc的内容。我的期望是,当sc.hasNext()返回false时,sc.nextInt()将不会引用任何内容。