在我的java代码中,当我尝试获取字符串形式的输入时,所以Scanner.next()和当我运行它时< code >线程" main " Java . util . nosuchelementexception中的异常这是我的代码
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.*;
public class App {
static int choice;
static Thread t;
static boolean isCompleteLoading;
public static void main(String[] args) throws Exception {
System.out.println();
mainMenu ();
}
static void Register () throws FileNotFoundException, IOException {
Scanner input = new Scanner(System.in);
Student student1 = new Student();
System.out.println("\n\t\t\t\t\t\t WELCOME TO MAIN MENU");
System.out.println("\t\t\t\t\t\t ------------------------");
System.out.print("\t\tEnter Your Name: ");
student1.studentName = input.next();
System.out.print("\t\tEnter Your Phone Number: ");
student1.phoneNumber = input.nextDouble();
System.out.print("\t\tEnter Your address: ");
student1.address = input.next();
System.out.print("\t\tEnter Your school name: ");
student1.schoolName = input.next();
System.out.print("\t\tHow do you wish to pay");
System.out.print("\n\t\t\t 1.Full");
System.out.print("\n\t\t\t 2.Half");
System.out.print("\n\n\t\tEnter Your choice: ");
student1.paymentType = input.nextInt();
processing();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Person.txt"));
out.writeObject(student1);
input.close();
}
public static void processing() {
t=new Thread() {
public void run() {
System.out.print("Processing---------");
for(int i = 0;i <= 100;i++){
if(i < 10){
System.out.print(i+"%");
System.out.print("\b\b");
}
else if(i >= 10 && i <= 99){
System.out.print(i+"%");
System.out.print("\b\b\b");
}
else{
System.out.println(i+"%");
isCompleteLoading = true;
}
try {
t.sleep(100);
} catch(Exception e) {
}
}
}
};
t.start();
}
public static void mainMenu () throws FileNotFoundException, IOException {
Scanner in = new Scanner(System.in);
System.out.println("\t\t\t\t\t\t ANATHA STUDENT MANAGEMENT SYSTEM");
System.out.println("\n\t\t\t\t\t\t WELCOME TO MAIN MENU");
System.out.println("\n\n\t\t\t\t 1.Register New Student");
System.out.println("\t\t\t\t 2.Find Student");
System.out.print("\n\t\t\t Enter Your choice: ");
choice = in.nextInt();
in.close();
switch (choice) {
case 1:
Register ();
break;
default:
break;
}
}
}
错误
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at App.Register(App.java:27)
at App.mainMenu(App.java:90)
at App.main(App.java:15)
为什么会出现此错误?
在< code>Register()函数中,您尝试在< code>System.in上创建一个扫描器。但是,在< code>mainMenu()中调用< code>Register()之前,您需要关闭在< code>mainMenu()开头创建的扫描仪。由于Java中的< code>InputStreams的工作方式,这也关闭了< code>System.in,因此尝试在其上创建新的扫描器是行不通的。这就是为什么命令行程序最好只有一个扫描器——如果你在多个函数中需要它,你可以把它变成一个静态变量,或者把它作为这些函数的参数传递下去。