如何修复变量可能尚未初始化

时间:2019-03-24 13:40:12

标签: java

我正在尝试创建一种方法,如果用户输入一个包含在列表6中的1个单词,则该方法会散布布尔值。否则请提示用户,直到他输入1个正确的单词为止。

我尝试过使用带有switch的while循环,但是它似乎不起作用

  /**
     * If the user says yes or y or true, return boolean value of true
     * if the user says no or n or false, return boolean value of false
     * Display a prompt if user fails to write any of 6 above words until
     * the user does
     */
    public static boolean promptForYesNo(Scanner in, String prompt){
        boolean toReturn;
        boolean valid;
        String userAnswer;
        System.out.println(prompt + "Yes or No?");   
        userAnswer = in.next();
        userAnswer = userAnswer.toLowerCase();
        while (userAnswer.equals("yes") || userAnswer.equals("y") || 
               userAnswer.equals("true") ||userAnswer.equals("no") || 
               userAnswer.equals("n") || userAnswer.equals("false")){
            if (userAnswer.equals("yes") || userAnswer.equals("y") || 
                userAnswer.equals("true")){
                     toReturn = true;
            }
            else if(userAnswer.equals("no") || userAnswer.equals("n") || 
                    userAnswer.equals("false")){
                     toReturn = false;
            }
            else {
                System.out.println(prompt + "Yes or No?");   
                userAnswer = in.next();
                userAnswer = userAnswer.toLowerCase();
            }
        }
        return toReturn;
    }

2 个答案:

答案 0 :(得分:1)

上面的代码连续循环:满足条件时使用中断

while (conditions) {
        if (conditions) {
            toReturn = true;
            break;
        } else if (conditions) {
            toReturn = false;
            break;
        } else {
            System.out.println(prompt + "Yes or No?");
            userAnswer = in.next();
            userAnswer = userAnswer.toLowerCase();
        }
    }

答案 1 :(得分:0)

即使您初始化变量,它也不会满足您的意图。相反,您应该使用参数再次递归调用该方法,直到您期望用户的意图,例如:

 public static boolean promptForYesNo(Scanner in, String prompt){
            System.out.println(prompt + "Yes or No?");   
            String userAnswer = in.next();
            userAnswer = userAnswer.toLowerCase();
            if (userAnswer.equals("yes") || userAnswer.equals("y") || 
                    userAnswer.equals("true")){
                return true;
            }
            else if(userAnswer.equals("no") || userAnswer.equals("n") || 
                    userAnswer.equals("false")){
                return false;
            }
            else {
                return promptForYesNo(in, prompt);
            }
        }

我已经整理了一下您的代码。