我知道了,我不知道为什么线程“ main”中的Exception java.util.InputMismatchException ...我想创建一个菜单,并将用户输入的句子转换为pig latin。我如何正确读取一行而不会出现异常?

public class Main {

    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {


        String options = "1.Print the options\n2.Transform a sentence into PIG latin\n" +
                "3.quit";
        System.out.println(options);
        boolean quit = false;

        while (!quit) {
           int choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    System.out.println(options);
                    break;
                case 2:
                    encryptIntoPigLatin();
                    break;
                case 3:
                    quit = true;
                    break;
            }
        }
    }

    private static void encryptIntoPigLatin() {
        System.out.println("Please enter the sentence: ");
        String sentence = "";

        sentence = scanner.nextLine();

        System.out.println(sentence);
        StringTokenizer st = new StringTokenizer(sentence);
    }

    private static void printLatinWord(String s) {
        String firstLetter = s.substring(0, 1);
        StringBuilder result = new StringBuilder();

        result.append(s.substring(1) + firstLetter + "ay");
        System.out.println(result.toString());

    }
}

最佳答案

创建2个Scanners实例,一个用于菜单,另一个用于句子

private static Scanner scannerMenu = new Scanner(System.in);
private static Scanner scannerSentence = new Scanner(System.in);


您的问题是菜单和句子使用的是同一台扫描仪。请记住,在encryptIntoPigLatin()方法中使用的扫描仪也嵌套在while循环中。

关于java - 将其转换为 pig 拉丁语时,如何正确读取行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36665879/

10-10 10:53