Tony Stark Tony Stark - 1 month ago 5
Java Question

How do I make sure that the user enters a number between 0 and 10 only?

I have made an array with all my subjects called subjectName. The goal of this code is to make sure that the user only enters valid numbers (between 1.0 and 10.0). but I don't know how to do that. I created an if statement and make it return if the subjectname isn't between 0 and 10 but that doesn't work. I am not sure how I can tackle this.

EDIT: subjectName are the names of each subject so its a String. subjectGrade is a double. BOTH ARE ARRAYS. Forgot to mention that.

This is my code:

for (int i = 0; i < subjectName.length; i++) {
Scanner input = new Scanner(System.in);
System.out.print("What is your grade for: " + subjectName[i] + "? ");
subjectGrade[i] = input.nextDouble();

if ( subjectGrade[i] < 0.0 || subjectGrade[i] > 10.0) {
return;
}

Neo Neo
Answer

You should use a while loop. Ask the question while the grade is invalid.

while(subjectGrade[i] < 0.0 || subjectGrade[i] > 10.0)
{
    System.out.print("What is your grade for: " + subjectName[i] + "? ");
    subjectGrade[i] = input.nextDouble();
}

(Goes instead of the if)

Anyway, your mistake is that the return statement doesn't repeats last command or anything. It returns a value from a function...

Comments