在将其转换为猪拉丁语时,如何才能正确读取一行?

时间:2016-04-16 15:14:04

标签: java java.util.scanner

我得到了,我不知道为什么线程“main”中的异常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());

    }
}

1 个答案:

答案 0 :(得分:1)

创建2个扫描程序实例,一个用于菜单,另一个用于句子

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

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