运行时切换错误(Scanner和InputMismatchException)

时间:2014-09-22 02:22:05

标签: java switch-statement

当我将userOption = userInput.nextInt();添加到我的循环中时,我收到以下错误,在我按1并输入字符串后出现错误。如果我从代码中删除指示的部分它的工作原理。我添加该代码因为我想让用户选择他想要的选项,直到他按下9使userOption等于9,并结束程序。

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at labone.LabOne.main(LabOne.java:37)

代码:

package labone;

import java.util.Scanner;

public class LabOne {

    public static void main(String[] args) {

        Scanner userInput = new Scanner(System.in);

        System.out.println("Welcome To The String Editor!");
        System.out.println("");
        System.out.println("Please choose what you would like to do by choosing one of the options below:");
        System.out.println("1. Input String");
        System.out.println("2. Print Current String");
        System.out.println("");
        int userOption = 0;
        String stringInput = new String();


        while(userOption != 9){
            userOption = userInput.nextInt();

            switch (userOption) {
                case 1: stringInput = userInput.nextLine();
                    System.out.println(stringInput);
                    break;

                case 2: System.out.println(stringInput);
                    break;

                //case 3: stringInput = new StringBuilder(stringInput).reverse().toString();
                    // System.out.println(stringInput);
                    //break;

                default: ;
                    break;
            }

        }
    }
}

0 个答案:

没有答案