我基本上是在尝试填充 String[][]。 每当我使用扫描仪的 next() 函数时,它都会抛出异常。
你能帮忙吗?
public static void main(String[] args) throws NumberFormatException, Exception {
int k,i;
int n = Integer.parseInt(IO.promptAndRead("Bitte geben Sie eine Zahl zwischen 5 und 50 ein: ")); // any number between 5 and 50
String name= IO.promptAndRead("Bitte geben Sie Ihren Vor- und Zunamen ein: "); //for example "Hans Zimmermann"
n=n-1;
String[][] matrix = new String[n][n];
Scanner sc = new Scanner(name);
boolean b_switch = false;
for (i = 0; i<n;i++) {
b_switch = !b_switch;
if (b_switch == true) {
for (k = 0; k<n;k++) {
matrix[i][k] = sc.next();
}
if (i+1 < n){
matrix[i+1][k] = sc.next();
}
}
else {
for (k = n; k>0;k--) {
matrix[i][k] = sc.next();
}
if (i+1 < n){
matrix[i+1][k] = sc.next();
}
}
}
我的控制台输出:
Bitte geben Sie eine Zahl zwischen 5 und 50 ein: 15
Bitte geben Sie Ihren Vor- und Zunamen ein: asdf
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ep1_uebung6.Maender.main(Maender.java:25)
最佳答案
您收到 NoSuchElementException
,因为您在代码中使用 sc.next()
而不验证是否存在任何元素。
您应该在调用 sc.next()
之前检查是否存在,如下所示。
if (sc.hasNext()) {
matrix[i][k] = sc.next();
}
关于java - 使用 next() 时扫描仪中出现 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27004342/