是否可以在if语句中返回用户输入声明的double以便在main中使用?

时间:2017-01-28 20:13:51

标签: java

我希望再次提示用户是否输入了可接受范围(0-100)之外的双倍,直到输入有效。当输入被认为有效时,我想返回正确的输入值,但是返回的是第一个不正确的值。如何返回正确的输入,如if语句所接受的那样?非常感谢!

public class examscore {
    public static void main (String[] args) {
        Scanner console = new Scanner(System.in);
        double sumfin = finalscore(console); 
        System.out.println(sumfin); // if user input is initially invalid, but then corrected, the first, incorrect, value is printed
    }

    public static double finalscore (Scanner console) { 
        System.out.println();
        System.out.println("Input final exam score: ");

        while(!console.hasNextDouble()) { //prompts the user, if invalid input, to input again, until a valid value is input
            System.out.println("Please input a mark between 0 and 100. ");
            console.next();
        } 
        double examscore = console.nextDouble();

        if (examscore >=0 && examscore<= 100) {
            System.out.println();
            System.out.println("Exam Score = "+examscore);
        } else {
            System.out.println("Error:");
            finalscore (console);
        }
        return examscore; //an attempt to return the VALID exam score: fails
    }
}

3 个答案:

答案 0 :(得分:1)

do-while循环非常适合。例如:

Scanner console = new Scanner(System.in);
double userInput = 0;
do {
    System.out.println("Please input a mark between 0 and 100. ");
    try {
        userInput = console.nextDouble();
    } catch (InputMismatchException e) {
        System.out.println("Your input could not be interpreted as a floating-point number.");
    }
} while (userInput <= 0D || userInput >= 100D);

答案 1 :(得分:0)

您错过了将finalscore(控制台)的结果分配给else块内的考试核心。

        if (examscore >= 0 && examscore <= 100) {
            System.out.println();
            System.out.println("Exam Score = " + examscore);
        } else {
            System.out.println("Error:");
            examscore = finalscore(console);
        }

答案 2 :(得分:0)

您可以使用循环或递归调用来完成此操作。我更喜欢递归调用:

private static double getValidScore(Scanner console) {
    System.out.println();
    System.out.println("Input final exam score: ");
    try {
        double score = Double.parseDouble(console.nextLine());
        if (score >= 0 && score <= 100) {
            return score;
        }
    } catch (NumberFormatException nfe) {}
    System.out.println("Please input a mark between 0 and 100.");
    return getValidScore(console);
}