I am trying to figure out how not to include invalid entries from being counted.
I need to enter 5 scores and want "score count" to 5, but the code I made only enters 4 "score counts", including the invalid entry. I am not required to enter the invalid entry and have no idea on how to exclude the invalid entries from being counted as scores.
Here is the code below.
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
Scanner sc = new Scanner(System.in);
String choice = "y";
// get a series of test scores from the user
while (!choice.equalsIgnoreCase("n"))
{
// initialize variables
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
System.out.println("Enter the number of test score to be entered: ");
int numberOfTestScores = sc.nextInt();
for (int i = 1; i <= numberOfTestScores; i++)
{
// get the input from the user
System.out.print("Enter score " + i + ": ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount = scoreCount + 1;
scoreTotal = scoreTotal + testScore;
}
else if (testScore != 999)
System.out.println("Invalid entry, not counted");
sc.nextLine();
// display the score count, score total, and average score
}
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.println();
System.out.println("Enter more test scores? (y/n)");
choice= sc.next();
}
}
}
Here is an example of the file being run.
Please enter test scores that range from 0 to 100. To end the
program enter 999. Enter the number of test score to be
entered: 5 Enter score 1: 66 Enter score 2: 85
Enter score 3: 99 Enter score 4: 79 Enter score 5: 457
Invalid entry, not counted
Score count: 4 Score total: 329 Average score: 82.0
Enter more test scores? (y/n)
Simply decrement the loop iteration variable i if it is an invalid score, so you re-ask for that score. So change this:
else if (testScore != 999)
System.out.println("Invalid entry, not counted");
to this:
else if (testScore != 999) {
System.out.println("Invalid entry, not counted");
i--;
}
Related
Here is the problem with my output:
Enter number of students: 3
Enter the grade for student 1:
-2
Invalid grade, try again...
Enter the grade for student 2:
-3
Invalid grade, try again...
Enter the grade for student 3:
110
Invalid grade, try again...
The average is 35.0
But in the sample output session as follow:
Enter number of students: 3
Enter the grade for student 1:
55
Enter the grade for student 2:
108
Invalid grade, try again...
Enter the grade for student 2:
56
Enter the grade for student 3:
57
The average is 56.0
Can you see the -2, the -3 and 110 did not break the loop and it kept asking for new input? Instead of showing 108 on the sample and immediately break the loop and ask user to prompt the input of student 2 again.
Here is my code:
public static int theSumOfGrade(int[] newArray, int grade) {
int sumGrade = 0;
for(int i = 0; i < newArray.length; i++) { // for i < array length
sumOfGrade += newArray[i]; // the sum will be added up with all the values inside the array
}
return sumOfGrade;
}
public static int[] getNumberOfStudentsArray(Scanner input) { // Number of students input method
System.out.printf("Enter number of students: "); // Prompt the number of students from the user
int numberOfStudents= input.nextInt(); // Scanner Object in with numberOfStudents variable
int studentGrades[] = new int[numberOfStudents]; // Assign to new Array
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the grade for student " + (i+1) + ":" );
studentGrades[i] = input.nextInt();
// for (int j = 0; j < studentGrades.length; j++) {
// }
if (studentGrades[i] < 0 || studentGrades[i] > 100) {
System.out.println("Invalid grade, try again");
continue;
}
}
return studentGrades;
} // end of getNumberOfStudentsArray()
When the input is wrong then int i should not get the increment. So you can do it as below:
for (int i = 0; i < numberOfStudents;) { // removed increment from here
System.out.println("Enter the grade for student " + (i+1) + ":" );
studentGrades[i] = input.nextInt();
if (studentGrades[i] < 0 || studentGrades[i] > 100) {
System.out.println("Invalid grade, try again");
continue;
}
i++; // Increment only when entered value is correct
}
I can't get the program to stop and display the message below if a -1 is entered to kill the loop before it starts. The program will also, not flow in to the while loop if a different integer is entered. I seem to have misplaced my curly brackets somewhere because the last 2 get errors.
public static void main(String[] args)
{
double score;
double total = 0.0;
double average;
int scoreCount = 0;
// create the Scanner object. Name it stdin
Scanner stdin = new Scanner(System.in);
// title at the top of the output
System.out.println (" score report");;
do{
// read the first score
System.out.printf ("Enter a score (1-100, -1 to quit)"
+ ": ", scoreCount);
score = stdin.nextDouble();
if (score == -1)
{
System.out.println ("Nothing entered.");
}
while((score = stdin.nextDouble()) != -1.0)
{
if (score<-1 || score>100)
{
System.out.println ("Illegal score. Try again");
System.out.printf ("Enter a score (1-100, -1 to quit)"
+ ": ", scoreCount);
}
else
{
System.out.printf ("Enter a score (1-100, -1 to quit)"
+ ": ", scoreCount);
scoreCount++;
total += score;
}
// end of for loop
average = total / scoreCount; //equation
System.out.printf ("\nThe average score for %d students is %8.2f\n",
scoreCount, average);
}
} // end of main
} // end of class definition
Based on what I understand, the problem has a simple solution. To exit the loop, simply use break:
if (score == -1)
{
System.out.println ("Nothing entered.");
break;
}
Also, based on the code, the "do" statement isn't really required. Simply use a regular while loop.
The code as posted will not compile. Here is a correct function to enter a bunch of numbers from 0 to 100 and calculate the average. The program will quit when -1 is entered. I have added comments to the code.
public static void main(String[] args)
{
double score;
double total = 0.0;
double average;
int scoreCount = 0;
// create the Scanner object. Name it stdin
Scanner stdin = new Scanner(System.in);
// title at the top of the output
System.out.println (" score report");
//Request the first score
System.out.printf ("Enter a score %d (1-100, -1 to quit)"
+ ": ", scoreCount+1);
//read the first score
score = stdin.nextDouble();
do{
//check the entered score and decide what to do.
if (score == -1)
{
System.out.println ("Nothing entered.");
break;
} else if (score<-1 || score>100)
{
System.out.println ("Illegal score. Try again");
System.out.printf ("Enter a score %d (1-100, -1 to quit)"
+ ": ", scoreCount+1);
}
else
{
scoreCount++;
total += score;
// The entered score is good ask for the next one
System.out.printf ("Enter a score %d (1-100, -1 to quit)"
+ ": ", scoreCount+1);
}
}while((score = stdin.nextDouble()) != -1.0); // Here we read the input.
// end of the program.
average = total / scoreCount; //equation
System.out.printf ("\nThe average score for %d students is %8.2f\n",
scoreCount, average);
} // end of main
You need a "while" condition at the end of your do loop. This is why it is called a do-while loop. Without the while condition, you should get a compile-time error. Here is an example:
double score;
double total = 0.0;
double average;
int scoreCount = 0;
// create the Scanner object. Name it stdin
Scanner stdin = new Scanner(System.in);
// title at the top of the output
System.out.println ("Score Report");
do{
// read the first score
System.out.println("Enter a score (0-100 or -1 to quit)"
+ ": " + scoreCount);
score = stdin.nextDouble();//Retrieve the score.
if(score == -1) {
System.out.println("Bye!");
}
if (score<-1 || score>100)//Here is the if statement that makes the user enter another score if it is illegal
{
System.out.println("Illegal score. Try again");
continue; //A continue statement will start the loop over again from the top!
}
else if(score >= 0 && score <= 100 && score != -1)
{
scoreCount++;
total += score;
}
// end of for loop
average = total / scoreCount; //equation
System.out.println();
System.out.printf ("\nThe average score for %d students is %8.2f\n",
scoreCount, average);
System.out.println();
}while(score != -1); //Runs "while" the score != -1
Here is a sample of the possible output of this program:
Score Report
Enter a score (0-100 or -1 to quit): 0
50.0
The average score for 1 students is 50.00
Enter a score (0-100 or -1 to quit): 1
50.0
The average score for 2 students is 50.00
Enter a score (0-100 or -1 to quit): 2
-90
Illegal score. Try again
Enter a score (0-100 or -1 to quit): 2
50.0
The average score for 3 students is 50.00
Enter a score (0-100 or -1 to quit): 3
-1
Bye!
The average score for 3 students is 50.00
As you can see here, you if statement changes to:
if (score<-1 || score>100)//Here is the if statement that makes the user enter another score if it is illegal
{
System.out.println("Illegal score. Try again");
continue;
}
The continue statement will force the loop to start at the beginning without executing the rest of the code in the loop. This will help you avoid invalid input.
At the end of the do loop you also need this while condition:
}while(score != -1);
Now the loop will only continue so long as the score is not equal to negative 1. If the score is equal to -1, you can also inform the user that they are exiting the program in your code:
if(score == -1) {
System.out.println("Bye!");
}
You can change your else statement to an else if statement to execute if the numbers entered are in the range of 0 to 100, or else the -1 entry would be counted as a score:
else if(score >= 0 && score <= 100 && score != -1)
{
scoreCount++;
total += score;
}
// end of for loop
You're also not exiting your loop like you say you are above. The average will be counted every time you iterate through your loop. Put the code that displays the average outside of your loop:
}while(score != -1);
average = total / scoreCount; //equation
System.out.println();
System.out.printf ("\nThe average score for %d students is %8.2f\n",
scoreCount, average);
Now the output will look something like this:
Score Report
Enter a score (0-100 or -1 to quit): 0
50.0
Enter a score (0-100 or -1 to quit): 1
70.0
Enter a score (0-100 or -1 to quit): 2
90.0
Enter a score (0-100 or -1 to quit): 3
-1
Bye!
The average score for 3 students is 70.00
If you want a message to be displayed ONLY when -1 is entered as the first option do:
if(score == -1 && scoreCount == 0) {
System.out.println("Bye!");
}
Hi everyone I'm a newbie in Java and I have a sample problem. I also have my own solution. Is there any other better way to solve this problem?
In far far away kingdom, there were battles of numbers. The king in that kingdom asks you to create a program that will determine the winner / champion of that event. The number of contestant is undetermined. The winner of the match is usually the BIGGEST number. The match is a single elimination. The sequence of the match is First IN vs Last IN, Second In vs Last Second In, etc... If there are no opponents for a particular number, he or she will be considered as default winner.
Sample Output:
Enter the Number of Contestant: 5
Enter Contestant # 1: 50
Enter Contestant # 2: 30
Enter Contestant # 3: 8
Enter Contestant #4: 11
Enter Contestant #5: 20
Simulation:
Round 1: 50 vs 20 Winner is: 50
Round 2: 30 vs 11 Winner is: 30
Round 3: Default Winner is: 8
Next …
Round 4: 50 vs 8 Winner is: 50
Round 5: Default Winner is 30
Next …
Round 6: 50 vs 30 Winner is: 50
Champion: 50
Total Bracket Matches: 3
Total Rounds: 6
My solution:
import java.util.Scanner;
public class BattleofNumbers{
public static void main(String[] args){
double num1, num2, num3, num4, num5;
double chal1, chal2, chal3, champion;
double bracket, round = 0;
System.out.println("Please Enter 5 Numbers: ");
System.out.println("");
Scanner in = new Scanner(System.in);
num1 = in.nextDouble();
num2 = in.nextDouble();
num3 = in.nextDouble();
num4 = in.nextDouble();
num5 = in.nextDouble();
System.out.println("");
if (num1 > num5){
chal1 = num1;
round++;
System.out.println("Round 1 Winner: " + chal1);
}
else{
chal1 = num5;
round++;
System.out.println("Round 1 Winner: " + chal1);
}
if (num2>num4){
chal2 = num2;
round++;
System.out.println("Round 2 Winner: " + chal2);
}else{
chal2 = num4;
round++;
System.out.println("Round 2 Winner: " + chal2);
}
if (chal1>num3){
chal3 = chal1;
round++;
System.out.println("Round 3 Winner: " + chal3);
}else{
chal3 = num3;
round++;
System.out.println("Round 3 Winner: " +chal3);
}
if (chal3 > chal2){
champion = chal3;
round++;
System.out.println("Round 4 Winner: " + champion);
}else{
champion = chal2;
round++;
System.out.println("Round 4 Winner: " + champion);
}
bracket = round / 2;
System.out.println("=====================");
System.out.println("The Champion: " + champion);
System.out.println("No. of Rounds: " + round );
System.out.println("No. of Brackets: " + bracket);
}
}
I tried a small implementation using arrays and I would call it semi-recursion. I'm sure it's not perfect, but it's a more generic approach because the amount of input numbers is dynamic and the condition check programmed only once. Feel free to give feedback on this, maybe someone has an idea to perform each check recursively.
import java.util.Scanner;
public class BattleofNumbers {
double[] nums;
int amount, round = 0;
double champ;
Scanner in;
public BattleofNumbers() {
in = new Scanner(System.in);
initValues();
processGame();
}
public void processGame() {
champ = calcChamp(nums);
System.out.println("=====================");
System.out.println("The Champion: " + champ);
System.out.println("No. of Rounds: " + round);
System.out.println("No. of Brackets: "
+ (int) Math.ceil((double) round / 2));
}
private void initValues() {
System.out.println("Please enter amount of numbers:");
amount = in.nextInt();
nums = new double[amount];
for (int i = 0; i < amount; i++) {
System.out.println("Please enter " + (i + 1) + ". number:");
nums[i] = in.nextDouble();
}
System.out.println("");
}
public double calcChamp(double[] nums) {
double[] nexts = new double[(int)Math.ceil(((double) nums.length / 2))];
for (int first = 0, second = (nums.length - 1); first <= second; first++, second--) {
if (nums[first] > nums[second]) {
nexts[first] = nums[first];
} else {
nexts[first] = nums[second];
}
round++;
System.out
.println("Winner of round " + round + ": " + nexts[first]);
}
if (nexts.length == 1) {
return nexts[0];
} else {
return calcChamp(nexts);
}
}
public static void main(String[] args) {
new BattleofNumbers();
}
}
I don't know how experienced you are, but you should use arrays instead of 5 single variables: double[] nums = new double[5];. Also, the variable "brackets" isn't needed because it is always round/2 so you can replace it: System.out.println("No. of Brackets: " + round/2);
Because line 2 and line 3 of every if-else-block are used in both the if- and the else-block, you should outsource them (and thereby reduce the amount of code):
if (num1 > num5){
chal1 = num1;
// round++;
// System.out.println("Round 1 Winner: " + chal1);
}
else {
chal1 = num5;
// round++;
// System.out.println("Round 1 Winner: " + chal1);
}
round++;
System.out.println("Round 1 Winner: " + chal1);
"round" seems to be constant at 4. You could stop counting it up and just declare it with 4: double round = 4;
This solution shows you how you can use ArrayList for such things (and how it is unlikely to be used in real code):
import java.util.ArrayList;
import java.util.Scanner;
public class Prog{
public static void main(String[] args){
ArrayList<Double> nums = new ArrayList<Double>();
Scanner in = new Scanner(System.in);
System.out.println("How many contestants are there? ");
int size = in.nextInt();
while(size-- > 0){
System.out.println("Contestant: ");
nums.add(in.nextDouble());
}
while(nums.size() > 1){
System.out.println("ROUND STARTED, contestants are: " + nums);
int i = 0;
while(i < nums.size()){
nums.set(i, Math.max(nums.get(i), nums.get(nums.size()-1)));
if(i != nums.size() - 1)
nums.remove(nums.size() -1);
i++;
}
}
System.out.println("Competition has ended, the winner is: " + nums.get(0));
}
}
I am building a grade calculator in Java, I am having trouble adding a couple features to it, and it appears that I keep mucking it up too while I try to make changes. I have been working on it all week, and started over in the book and the powerpoint slides, and I just feel like there are just some pieces I am still not getting.
I need to make sure the invalid scores, reenter error shows up everytime a negative score is inputted. And then I need to calculate the class statistics of Average, Lowest and Highest scores. So basically a collaboration of how ever much data was inputted which could be any number of exams or students.
Here is my code, please let me know if you need more info. I am really new to this so I apologize that it is not the greatest.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args){
double examAverage = 0, scoresEntered = 0, examSum = 0;
double totalExamSum = 0, allScoresEntered = 0;
//variables for input
Scanner GC = new Scanner(System.in);
//Scanner for integer inputs
System.out.println("Welcome to Grade Calculator!" +"\n");
System.out.println("Please enter the number of students:");
int numberStudents = GC.nextInt();
//number of students input
System.out.println("Please enter the number of exams:");
int numberOfExams = GC.nextInt();
//number of exams input
for (int i = 1; i <= numberStudents; i++) {
Scanner name = new Scanner(System.in);
//scanner for student name input
//Scanner for name input
System.out.println("\n--------------------------------------");
System.out.print("Enter student " + i + "'s name : " );
String studentname = name.nextLine();
//student name input
System.out.print("Enter exam scores : ");
for (int j = 0; j < numberOfExams; j++) {
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);}
//score input and sum of all input scores
do{
System.out.println("Invalid exam scores, reenter: ");
scoresEntered =GC.nextDouble();
} while(scoresEntered<0);
//my attempt at the Invalid exam score error
examAverage = (examSum/numberOfExams);
//examaverage calculator
System.out.println("\n--------------------------------------");
System.out.println("Grade Statistics for " + name);
System.out.println(" Average : " + examAverage);
//Conditions and print outputs below for grade averages
if(examAverage <= 100 & examAverage >=90){
System.out.println(" Letter Grade: A");
System.out.println(" " + name + " gets 4 stars! ****");
examAverage = 0;
examSum = 0;}
else if(examAverage <=89.99 & examAverage >=80){
System.out.println(" Letter Grade: B");
System.out.println(" " + name + " " + " gets 3 stars! ***");
examAverage = 0;
examSum = 0;}
else if(examAverage <=79.99 & examAverage >=70){
System.out.println(" Letter Grade: C");
System.out.println(" " + name + " " + " gets 2 stars! **");
examAverage = 0;
examSum = 0;}
else if(examAverage <=69.99 & examAverage >=60){
System.out.println(" Letter Grade: D");
System.out.println(" " + name + " " + " gets 1 stars! *");
examAverage = 0;
examSum = 0;}
else if(examAverage <=59.99 & examAverage >=50){
System.out.println(" Letter Grade: F");
System.out.println(" " + name + " " + " gets 0 stars!");
examAverage = 0;
examSum = 0;}
//still need class statistics as well as help with the invalid exam scores, reenter error.
}
}
}
What jumps out at me is the looping around your score input:
for (int j = 0; j < numberOfExams; j++)
{
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);
}
//score input and sum of all input scores
do
{
System.out.println("Invalid exam score, reenter: ");
scoresEntered = GC.nextDouble();
} while(scoresEntered < 0);
I've deliberately reformatted what you posted to try to make the problem more obvious. What you appear to be doing is reading in all the scores. Then, regardless of what was entered, you tell the user the exam scores are invalid and ask them to re-enter. Remember, a do...while loop always executes at least once. If the first re-entered score is above zero, that is all you'll read as the while condition is then satisfied.
If you are trying to validate each score before it is added to examSum, you need something more like this:
for (int j = 0; j < numberOfExams; j++)
{
while ((scoresEntered = GC.nextDouble()) < 0)
System.out.println("Invalid exam scores, reenter: ");
examSum = (examSum + scoresEntered);
}
So I've used System.out.print("Enter more test scores? (y/n): "); yet when I run it and all the scores are summarizes the user isn't given the chance to do it again here is my code. Do you guys think I may have put it in the wrong place.
public class TestScoreApp
{
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
outerLoop:
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
if (setNumber == counter)
{
break outerLoop;
}
//End of test scores while loop
}
userAnswer = sc.next();
}
}// end of do loop
while(userAnswer.compareTo("y") == 0 );
System.out.print("Enter more test scores? (y/n): ");
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
}
I dont know what exactly you want to do, if you want to ask if the user want to add more scores after the default scores (that user set on beggining) so this is the answer:
import java.text.NumberFormat;
import java.util.Scanner;
public class TestScoreApp {
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
// declarations
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
// outerLoop:
// do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999) {
do { // put the loop condition below
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100) {
scoreCount += 1;
scoreTotal += testScore;
setNumber--;
} // Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
// if (setNumber == counter) {
// break outerLoop;
// }
if (setNumber == counter) { // test if the counter reached zero
System.out.print("Enter more test scores? (y/n): "); // ask if the user want to add more
userAnswer = new Scanner(System.in).next(); // read the input
if (userAnswer.toCharArray()[0] == 'y') { // if yes, do
setNumber += 1; // add +1 to setNumber, so user can add more one score
}
}
} while (setNumber > 0);
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n" + "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n" + "Average score: "
+ averageScore + "\n"
// Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n" + "Min score: " + min + "\n";
System.out.println(message);
}
}
There are several modifications to be done in the program.
When you are asking user to enter the choice for inputting more, you should accept his/her choice in your userAnswer variable before closing off the do-while loop SO THAT THE USER CHOICE CAN BE CHECKED AFTER EACH ITERATION!
There is no need to break the OUTER-LOOP without checking user's input!
scoreCount & scoreTotal need to be initialised with 0 again in the beginning of the do-while loop.
The corrected program along with the imports needed :-
import java.text.NumberFormat;
import java.util.Scanner;
public class JavaApplication7 {
public static void main(String[] args) {
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreCount = 0,scoreTotal = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
scoreCount=0;
scoreTotal=0;
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
System.out.print("Enter more test scores? (y/n): ");
userAnswer=sc.next(); // Single Error----Only corrected piece of code.
}while(userAnswer.compareTo("y") == 0 );
// end of do loop
}
}
You are asking the user:
System.out.print("Enter more test scores? (y/n): ");
after you exit from the while loop. This won't work. Just put this line exactly before:
userAnswer = sc.next();