-2

如果你们发现这有什么问题,请告诉我。我收到此错误:

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);
    }

}
4

2 回答 2

1

首先,只有在案例 8 上断开开关才会导致奇怪的事情发生。您应该在每个案例之后添加一个中断,并System.exit(0)为案例 8 添加。

其次,您是否在扫描仪提示符处输入了任何内容?如果您键入输入结束符号,则会发生这种情况。另外,System.in对应的流是什么?如果您从真正的命令行调用它并且不键入输入结束,我看不出这是怎么发生的。

于 2013-07-25T19:42:53.793 回答
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.
}
于 2013-07-25T19:42:36.090 回答