2

I'm work on a homework question and am having an issue with a part of my loop

/**
 * Created by wilson on 2/25/2014.
 */
import java.util.Scanner;
public class GradesDemo {
    public static void main(String[] args) {
        Grades grade = new Grades();
        String name;
        double score = 0;
        boolean invalid = true;
        Scanner keyboard = new Scanner(System.in);
        //One loop iteration for each student

        for (int i = 0; i < 5; i++) {
            invalid = true;
            //Asks for student name, and stores to array
            System.out.println("Student's Name:");
            name = keyboard.nextLine();
            grade.setName(name, i);

            //while loop to check if score entered by user is valid
            while (invalid == true) {
                System.out.println("Student's Score:");
                score = keyboard.nextDouble();
                //Check if score entered was valid. If not, user will be asked again
                if (score >= 0 && score <= 100)
                    invalid = false;
                else
                    System.out.println("Score is invalid. Must be between 0-100. Try again.");
            }
            grade.setScore(score, i);
            //Calculate grade
            grade.findGrade(i);
        }

        for (int i = 0; i <5; i++) {
            System.out.println(grade.toString(i));
        }
    }
}

Output Sample:

Student's Name:
John Doe
Student's Score:
88
Student's Name:
Student's Score:

As you can see, in the second iteration of the loop, it skips waiting for user input under Student name directly to student score, causing an error.

1 Answers1

1

Use BufferReader instead of using Scanner it will resolve all those problem.

ashokramcse
  • 2,751
  • 2
  • 16
  • 40