如果你们发现这个问题,请告诉我。我收到了这个错误:
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 interaction.menu(interaction.java:15)
at driver.main(driver.java:9)
第15行是selection = scan.nextInt();
在while循环内部。 main只包含一个在此类中调用此方法的方法。
//provides the interface to be used
public void menu(){
Scanner scan = new Scanner(System.in);
database db = new database();
int selection;
while(true){
hugeTextBlock();
selection = scan.nextInt();
switch(selection){
//creates a new course
case 1: db.addCourse();
//removes a course
case 2: db.deleteCourse();
//enroll a student
case 3: db.enrollStudent();
//delete a student
case 4: db.deleteStudent();
//register for a course
case 5: db.registerStudent();
//drop a course
case 6: db.dropCourse();
//check student registration
case 7: db.checkReg();
//quit
case 8: break;
default: System.out.println("default action");
}
}
}
下面是另一个类中的addCourse方法。我自己运行它并且工作得很好。
//creates a new course
public void addCourse(){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:StudentRegistration_DSN");
Statement st = conn.createStatement();
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the course title: ");
String title = scan.nextLine();
System.out.println("Please enter the course's code: ");
String code = scan.next();
st.executeUpdate("insert into course values('"+code+"','"+title+"')");
ResultSet rs = st.executeQuery("select * from course");
code = "";
title = "";
System.out.println("This is the relation as of current changes.");
while (rs.next())
{
code=rs.getString(1);
title=rs.getString(2);
System.out.println("Code: " + code + " Title: " + title);
}
rs.close();
st.close();
conn.close();
scan.close();
}
catch (Exception e){
System.out.println(e);
}
}
答案 0 :(得分:1)
首先,只有打开案例8上的开关才会导致奇怪的事情发生。您应该在每个案例后添加一个中断,并为案例8添加System.exit(0)
。
其次,您是否在扫描仪提示符处键入了任何内容?如果键入输入结束符号,则会发生这种情况。此外,System.in
对应的流是什么?如果你从一个真正的命令行调用它并且不输入结束输入,我不知道这是怎么发生的。
答案 1 :(得分:0)
异常告诉Scanner.nextInt
没有要读取的int。您应确保扫描仪将返回的下一个事实上是一个int。请参阅Scanner.hasNextInt。
while (!scanner.hasNext()) {
// sleep here
}
if (scanner.hasNextInt()) {
selection = scan.nextInt();
} else {
selection = 0;
scan.next(); // reads the garbage.
}