处理异常的流程

时间:2016-05-20 01:29:00

标签: java exception

有人知道控制台输出在打印exception之前再次显示菜单的原因吗?

我输出应该是:

1. item 1
2. item 2
3. Quit
Please choose a item:
WRONGINPUT         <---- user input
Invalid input      <---- where I want the exception shows
1. item 1
2. item 2
3. Quit
Please choose a item:

然而,我得到的是:

1. item 1
2. item 2
3. Quit
Please choose a item:
WRONGINPUT         <---- user input
1. item 1
2. item 2
3. Quit
Please choose a item:
Invalid input      <---- why the exception is shown here?

代码如下所示:

    // code omitted

    Scanner scanner = new Scanner(System.in);
    int mainMenu = -1;
    do {    
        try {
            System.out.println("1. item 1");
            System.out.println("2. item 2");
            System.out.println("3. Quit");
            System.out.println("Please choose a item:");
            mainMenu = scanner.nextInt();
        } catch (InputMismatchException e) {
            scanner.nextLine(); 
            System.err.println("Invalid input");        
        }
            if (mainMenu == 1)
                // do something
            else if (mainMenu == 2)
                // do something
            else if (mainMenu == 3)
                System.out.println("Quitting...");
    } while (mainMenu != 3);

console output

2 个答案:

答案 0 :(得分:0)

这是答案。请运行此程序。

package java7.demo;

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

public class Test {

    public static void main(String args[]){
        int mainMenu = -1;
         Scanner scanner = new Scanner(System.in);

    do {    
        try {
            System.out.println("1. item 1");
            System.out.println("2. item 2");
            System.out.println("3. Quit");
            System.out.println("Please choose a item:");
            mainMenu = scanner.nextInt();
            if (mainMenu == 1){
                // do something
            }
            else if (mainMenu == 2){

            }
                // do something
            else if (mainMenu == 3){
                System.out.println("Quitting...");
            }else{
                throw new InputMismatchException();
            }
        } catch (InputMismatchException e) {

            System.err.println("Invalid input"); 
            scanner.nextLine(); 
        }

    } while (mainMenu != 3);
    }
}

您只需要在err print statement下更改scanner.nextLine()。

答案 1 :(得分:0)

当我在命令中运行时,我的代码在顺序上没有任何错误。

我发现原因是System.err.println在Eclipse中很重要。当我将其更改为System.out.println时,我会得到正确的输出顺序。但我认为没有必要,因为这是Eclipse的问题。

Console Printing Order in Eclipse

此链接告诉我原因。无论如何,谢谢你的帮助。干杯