Question

I am writing an object oriented program that takes in the name and values for a certain object then gives the total sum of the values and its average. So the purpose of the program is to have the user input as many values as he or she wants and then enter a value less than 0 to exit. Then program churns out the total sum of entered values and its average. Problem is the loop takes in the sentinel value as a value for the object.
How do I prevent this?

import java.util.Scanner;

public class TestStudent {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);    
        Student s = new Student();
        s.setName(sc.nextLine());
        System.out.println("Please enter in scores and to stop enter a score less than 0");
        int x = 0;
        while (x >= 0) {
            x = sc.nextInt();
            if(x >= 0) {
                s.addQuiz(sc.nextInt());        
            }
            else break;
        }
        System.out.println(s.getName());
        System.out.println(s.totalScore());
        System.out.println(s.averageScore());
    }
}

These are the mutators and accessors I am using.

public int totalScore() {
    return quiz;
}

public void addQuiz(int score) {
    quiz = quiz + score;
    num++;
}

public double averageScore() {
    average = quiz/num;
    return average;
}
Was it helpful?

Solution

Read the loop you have written more closely. You are calling nextInt() twice, once to get the value for x and another time to call the addQuiz() method:

while (x >= 0) {
    x = sc.nextInt();
    if (x >= 0) {
        s.addQuiz(sc.nextInt());
    }
    else break;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top