gpt4 book ai didi

java - 扫描仪 : Exception in thread "main" java. util.NoSuchElementException

转载 作者:行者123 更新时间:2023-12-02 11:55:18 28 4
gpt4 key购买 nike

我正在尝试创建一个实用程序类,以使用java.util.Scanner标准控制台获取输入

package dbasics;

import java.util.*;


public class Utils {

public static int getNumericInput() {
System.out.println("Enter a integer ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
return n;
}

public static int[] getNumericArrayInput(int n) {
//System.out.println("Enter "+n+" integers seperated by a whitespace ");
int[] numbers = new int[n];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < n; i++) {
numbers[i] =scanner.nextInt();
}

scanner.close();
return numbers;
}

}

在另一个类中调用静态方法时,方法getNumericInput()工作正常,但是以下方法getNumericArrayInput(int n)会导致一个异常(exception)。

package dbasics;

public class Demo {

public static void main(String[] args) {

int n = Utils.getNumericInput();
System.out.println("Number "+n);
int arr[] = Utils.getNumericArrayInput(n);
for(int i : arr) {
System.out.println(i);
}
}

}

运行此命令会导致以下异常

Enter a integer 
5
Number 5
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at dbasics.Utils.getNumericArrayInput(Utils.java:21)
at dbasics.Demo.main(Demo.java:9)

我注意到的有趣的事情是,如果我注释掉第一个输入过程,数组输入就可以正常工作

最佳答案

您正在关闭导致异常的函数中的扫描仪:试试这个:

import java.util.*;


class Utils {

public static int getNumericInput() {
System.out.println("Enter a integer ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
return n;
}

public static int[] getNumericArrayInput(int n) {
int[] numbers = new int[n];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < n; i++) {
numbers[i] =scanner.nextInt();
}

scanner.close();
return numbers;
}

}
public class cn {

public static void main(String[] args) {

int n = Utils.getNumericInput();
System.out.println("Number "+n);
try{
int arr[] = Utils.getNumericArrayInput(n);

for(int i : arr) {
System.out.println(i);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

更多信息请阅读this link

关于java - 扫描仪 : Exception in thread "main" java. util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47650468/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com