讓我知道你們是否看到有什麼問題。我得到這個錯誤:簡單的switch語句錯誤?
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();
正確的內循環。主要包含一個在這個類中調用這個方法的方法。
//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);
}
}
您可能應該在您的交換機中有一些中斷... –
請參閱http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html。 (尤其是,搜索該頁面的短語*通過*。) – ruakh