0
     while(flag)
     {       
        System.out.println("Press 1 to Add Student details");
        System.out.println("Press 2 to Display Student details");
        System.out.println("Press 3 to Sort");
        System.out.println("Press 4 to Search");
        System.out.println("Press 5 to Exit");
        System.out.println("Enter your choice: ");

        while(!sc1.hasNextInt())
        {
            System.out.println("Please enter proper Integer input!");
            sc1.next();
        }

        choice = sc1.nextInt();
      //more code..
    }

在上面的代码中,我从用户那里获取输入。如果用户输入除 int 以外的任何内容,则不被接受。假设给定一个字符串而不是一个 int,打印消息并且不再显示菜单。我希望在消息之后显示菜单。我该怎么做?

4

2 回答 2

1

这可能会帮助你

while (flag) {
    System.out.println("Press 1 to Add Student details");
    System.out.println("Press 2 to Display Student details");
    System.out.println("Press 3 to Sort");
    System.out.println("Press 4 to Search");
    System.out.println("Press 5 to Exit");
    System.out.println("Enter your choice: ");

    if (sc1.hasNextInt()) {
        choice = sc1.nextInt();
        //more code here
    } else {
        System.out.println("Please enter proper Integer input!\n");
        sc1.next();
    }
}

我添加了一个额外"\n"的内容以提高可读性。这样当打印警告时,选择不会在下一行打印。

于 2013-09-12T12:28:01.377 回答
0

您还需要在内部循环中有菜单系统输出。像这样:-

while(!sc1.hasNextInt())
{
    System.out.println("Please enter proper Integer input!");
    System.out.println("Press 1 to Add Student details");
    System.out.println("Press 2 to Display Student details");
    System.out.println("Press 3 to Sort");
    System.out.println("Press 4 to Search");
    System.out.println("Press 5 to Exit");
    System.out.println("Enter your choice: ");
    sc1.next();
}
于 2013-09-12T11:39:02.257 回答