使用do和switch提示输入

时间:2014-11-04 10:01:25

标签: java

public static void main(String[] args){
    char OperatorCode;
    int answer;
    int firstOperand;
    int secondOperand;
    String inputString;
    boolean quit = false;
    Scanner inLine = new Scanner(System.in);
    do{
        System.out.print("Enter the Operator Code (A,S,M or D): ");
        inputString = inLine.nextLine();
        OperatorCode = inputString.charAt(0);
        if (OperatorCode != 'Q'){
            inputString = inputString.substring(1, inputString.length());
            Scanner string = new Scanner(inputString);
            System.out.print("Enter the First Operand: ");
            firstOperand = string.nextInt();
            System.out.print("Enter the Second Operand: ");
            secondOperand = string.nextInt();
            switch (OperatorCode){
                case 'A' : answer = (firstOperand + secondOperand);
                           System.out.println(firstOperand + " + " + secondOperand + " is " + answer);
                case 'S' : answer = (firstOperand - secondOperand);
                           System.out.println(firstOperand + " - " + secondOperand + " is " + answer);
                case 'M' : answer = (firstOperand * secondOperand);
                           System.out.println(firstOperand + " * " + secondOperand + " is " + answer);
                case 'D' : answer = (firstOperand / secondOperand);
                           System.out.println(firstOperand + " / " + secondOperand + " is " + answer);
                           break;
            }               
        } else 
              quit = true;
    }while (!quit);
} 
}

我的代码似乎有什么问题?它输出第一个语句(?)很好,我可以在那里输入我想要的字符,但是当它转到第二个语句(?)(“输入第一个操作数。”)时,我收到一个错误,上面写着“

“输入第一个操作数:线程中的异常”main“java.util.NoSuchElementException”

有人可以指出我的错吗?

2 个答案:

答案 0 :(得分:0)

这可能是留下'\ n'的问题。也许这个问题可以帮到你:Scanner issue when using nextLine after nextXXX

答案 1 :(得分:0)

我建议你使用string.nextLine();而不是.nextInt();方法,因为当nextLine解析它时它不会处理EOL

为什么要将string作为参数传递给扫描仪类,

Scanner string = new Scanner(inputString);

我猜它可能是(System.in)

同样将break;添加到您的案例A,S和M中,如John建议的那样