Java新手 - 只是试图掌握它。该程序正在执行如下:
What's your age?23
23
What's your name?Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at king.getName(king.java:25)
at king.main(king.java:9)
它试图运行的代码如下:
import java.util.*;
public class king {
public static void main(String[] args){
System.out.println(getAge());
System.out.println(getName());
}
public static int getAge(){
System.out.print("What's your age?");
Scanner scanner = new Scanner(System.in);
String age = scanner.next();
scanner.close();
int numberAge = Integer.parseInt(age);
return numberAge;
}
public static String getName(){
System.out.print("What's your name?");
Scanner newScanner = new Scanner(System.in);
String name = newScanner.next();
newScanner.close();
return name;
}
}
答案 0 :(得分:9)
请勿使用scanner.close()
< - 错误来源!
删除行scanner.close()
和newScanner.close()
来自Java DOC:
当扫描仪关闭时,如果是源,它将关闭其输入源 实现Closeable接口。
这意味着它会关闭System.in
- 糟糕的选择!
从JDK中Scanner.java
的源代码,throwFor()
是:
private void throwFor() {
skipped = false;
if ((sourceClosed) && (position == buf.limit()))
throw new NoSuchElementException();
else
throw new InputMismatchException();
}
显然,如果我们已经到达输入的末尾,或者如果源被关闭,那么我们得到NoSuchElementException()
。我很确定因为position == buf.limit()
而不是sourceClosed
答案 1 :(得分:1)
试试这个:
public class King {
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
System.out.println(getAge(scanner));
System.out.println(getName(scanner));
}
public static int getAge(final Scanner scanner) {
System.out.print("What's your age?");
final String age = scanner.next();
final int numberAge = Integer.parseInt(age);
return numberAge;
}
public static String getName(final Scanner scanner) {
System.out.print("What's your name?");
final String name = scanner.next();
return name;
}
}
另请注意,java类应该大写。
答案 2 :(得分:1)
我认为alraedy @Aniket给出了一个非常好的答案。
import java.util.*;
代替import
java.util.Scanner;
,因此不会导入不必要的类。第二件事是你可以像我在示例中看到的那样Scanner
。(所以你可以关闭它)
import java.util.Scanner;
public class SO6 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
System.out.println(getAge());
System.out.println(getName());
scanner.close();
}
public static int getAge(){
System.out.print("What's your age?");
String age = scanner.next();
int numberAge = Integer.parseInt(age);
return numberAge;
}
public static String getName(){
System.out.print("What's your name?");
String name = scanner.next();
return name;
}
}
答案 3 :(得分:1)
首先,为了避免NoSuchElementException,您应该在使用Scanner.next()之前执行Scanner.hasNext()检查。其他评论,尤其是关于使用单个扫描仪的评论也很有用。