在使用char循环时无法停止

时间:2017-02-25 03:32:11

标签: java while-loop

以下是一个旨在将用户输入转换为字母分数的程序。该代码按预期工作,但我的" endGame"方法在我想要之前就开始运行。
    import java.util.Scanner; //我需要这个来获取用户输入

public class Grade {

public static void main(String[] args) {
    startGame(); // This creates my start game method
    endGame(); // this will end the game
    gradeLoop(); // This creates the letter grade determination
}

public static void startGame() {// Starts the startGame method
    System.out.println("Welcome to the Auto Score OneThousand");
    System.out.println("Please enter your score from 0  to 100 (or press 'E' to exit): ");
}

public static void gradeLoop() {

    String userInput; // assigns user input
    char letter = 'A'; // assign a char that will be updated with the user's
                        // letter grade
    double score = 0.0;
    boolean go = true;

    while (go) {
        Scanner keyboard = new Scanner(System.in); // Create a new Scanner
                                                    // to hold the input
        userInput = keyboard.nextLine();

        if (userInput.equals("E") || userInput.equals("e")) {
            go = false;
            endGame();
            break;
        } else {
            score = Double.parseDouble(userInput);// convert string to
                                                    // double
        }
        if (score >= 90 & score <= 100)

            letter = 'A';

        else if (score >= 80 & score <= 89)

            letter = 'B';

        else if (score >= 70 & score <= 79)

            letter = 'C';

        else if (score >= 60 & score <= 69)

            letter = 'D';

        else if (score >= 0 & score <= 59)

            letter = 'F';

        {

            System.out.println("You earned a letter grade of: " + letter + "\n\n");

            startGame();
        }
    }
}

public static void endGame() {
    System.out.println("Thank you, This ends your Auto Score OneThousand experiance");
}

}

1 个答案:

答案 0 :(得分:0)

将测试放在循环的开头。如

boolean go = true;
while (go) {
    System.out.print("Please enter your score from 0  to 100(enter E to exit):");
    String str = grades.next();
    if (str.equals("E")) {
        System.out.println("The program exits!");
        break;
    }
    y = Integer.parseInt(str);
    //following start to process the int y.
}

提示:您的代码中有额外的大括号,最好将其删除。