方法调用恢复流程 --Java

Method call resumes flow --Java

我的程序调用菜单需要用户输入以转到正确的方法,returns 到菜单以允许使用其他方法或退出程序

            System.out.println("Start of menu options");
            System.out.println("Enter your command (quit, print reverse, replace all, replace single, remove)");
            userChoice = sc.nextLine();
            if(userChoice.equalsIgnoreCase("print reverse")){
                printReverse(userString);

            }
            if(userChoice.equalsIgnoreCase("replace all")){
                replaceAll(userString);
            }
            if(userChoice.equalsIgnoreCase("remove")){
                remove(userString);
            }
            if(userChoice.equalsIgnoreCase("replace single")){
                replaceSingle(userString);
            }
            if(userChoice.equalsIgnoreCase("quit")){
                quit();
            }
            menu();

        }

reverse() 方法returns 用户进入菜单没有问题

            List<Character> temp = new ArrayList<>();
            for(char ch : a.toCharArray()){
                temp.add(ch);
            }
            Collections.reverse(temp);
            System.out.println("The new sentence is: "+temp.stream().map(i->i.toString()).collect(Collectors.joining()));
            menu();
        }

但其余方法似乎都绕过了扫描仪 .nextLine(),因为它们将在没有循环 menu() 命令的情况下结束程序,但在第二次循环时会提示用户输入扫描仪调用。

public static void replaceAll(String a){
            System.out.println("Enter Char");
            String charToBeReplaced = sc.next();
            System.out.println("New Char");
            String charReplacement = sc.next();
            userString = a.replaceAll(charToBeReplaced, charReplacement);
            System.out.println("Your new sentence is: " + userString);
            menu();
        }

通过调试器,当程序开始检查 userChoice 是否等于“退出”时,我可以看到 userChoice 为空,但程序运行了两个 println 命令

Scanner.next 直到空白,而 Scanner.nextLine 直到 \n。

例如) 首先,如果你在 replaceAll 方法中输入 strcharToBeReplaced 有 str
next 如果你输入str2char替换有str2你可以在输入str2时输入回车\n。
因为sc有\n,userChoice有\n。

参考https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/