I'm currently working on code that asks the users for their grades in a loop then outputs the highest, lowest, average, etc.
I'm having a bit of trouble figuring out how to show a letter grade next to their valid number grade. For example: 79 (C+).
If anyone can point me in the right direction what I need to do that'd be great.
import java.util.*;
public class Main {
public static void main(String[] args) {
/*
I know the code isn't the most efficient but im still learning how to use more methods so please
bear with me for the beginning of the semester for the time being.
*/
ArrayList<Double> invalidnums = new ArrayList<>();
ArrayList<Double> validnums = new ArrayList<>();
Scanner scan = new Scanner(System.in);
double totalinvalidGrade=0, totalvalidGrade=0;
double sum = 0;
//INPUT OF THE GRADES THROUGH THE ARRAYLIST
while (true) {
System.out.println("Enter a grade: ");
double grade = scan.nextInt();
if (grade <= (-2)) {
invalidnums.add(grade);
totalinvalidGrade++;
System.out.println("Error, Grade must be between (0-100); or -1 to finish");
} else if (grade >= 101) {
invalidnums.add(grade);
totalinvalidGrade++;
System.out.println("Error, Grade must be between (0-100); or -1 to finish");
}
else {
validnums.add(grade);
totalvalidGrade++;
}
if (grade == -1) {
break;
}
}
//Start of the GRADES SUMMARY:
//PRINTS THE AMOUNT OF VALID AND INVALID GRADES POSTED.
System.out.println("You submitted " +totalinvalidGrade+ " invalid grades");
System.out.println("You submitted " +totalvalidGrade+ " valid grades");
//PRINTS THE HIGHEST AND LOWEST GRADES ALONG WITH THE AVERAGE.
System.out.println("Highest Grade: "+Collections.max(validnums));
System.out.println("Lowest Grade: "+Collections.min(invalidnums));
for (double value : validnums) {
sum += value;
}
//return sum;
System.out.println("Average: "+sum);
//PRINTS THE LIST OF VALID AND INVALID GRADES:
System.out.println("Here are the "+totalvalidGrade+" valid grades: ");
for (Double valelement : validnums) {
System.out.println(valelement);
}
System.out.println("Here are the "+totalinvalidGrade+" invalid grades: ");
for (Double element : invalidnums) {
System.out.println(element);
}
}
}
//EOC
//SOURCES I USED TO HELP DEVELOP MY CODE AND UNDERSTAND:
//MAX AND MIN GRADES: https://www.tutorialspoint.com/find-maximum-element-of-arraylist-with-java-collections
//
This is my Java programming class assignment: Write a program, that takes users’ input and the number of students, and test scores. It should then average test scores and display them on the screen. (Wants us to do this using a nested loop).
The issue that I am having is when the program goes into the second loop the sum is still totaling the scores from the previous loop. so it is throwing off any student average calculated after the first one.
'Import java.util.Scanner;'
class Main { public static void main(String[] args) {
int ans, ans1;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("\n\nFor how many students do you have scores ? ");
ans = sc.nextInt(); //Number of Students
for (int x=1; x<=ans; x++) {
System.out.print("\n\nHow many test scores does student #" + x+" have? ");
ans1 = sc.nextInt(); //Number of scores entered
for (int z=1; z<=ans1; z++) {
double ans2;
System.out.print("\nEnter score "+z+" for student " +x+": ");
ans2 = sc.nextDouble();
sum += ans2 + 0; //Student Scores
}
double avg = sum/ans1;
System.out.printf("\nStudent #"+x+" Average Score: %.1f", avg);
}
}
}
Output:
For how many students do you have scores ? 2
How many test scores does student #1 have? 3
Enter score 1 for student 1: 84
Enter score 2 for student 1: 79
Enter score 3 for student 1: 97
Student #1 Average Score: 86.7
How many test scores does student #2 have? 3
Enter score 1 for student 2: 92
Enter score 2 for student 2: 88
Enter score 3 for student 2: 94
Student #2 Average Score: 178.0 //Average should be 91.3
You should reset the sum variable inside the loop.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int ans, ans1;
double sum = 0;
Scanner key = new Scanner(System.in);
System.out.println("\nHow many students have scores?: ");
ans = key.nextInt();
for(int i = 0; i < ans; i++){
System.out.print("\nHow many test scores does Student "+ (i+1) + " have?: ");
ans1 = key.nextInt();
for(int j = 0; j < ans1; j++){
double ans2;
System.out.print("\nEnter score " + (j + 1) + " for Student " + (i + 1) +": ");
ans2 = key.nextDouble();
sum += ans2;
}
double avg = sum/ans1;
System.out.printf("\nStudent " + (i + 1) + " Average score: %.1f", avg);
sum = 0; //add this line
}
}
}
The "sum" variable should be inside the ans loop as it must be reset for each student. :)
I am creating a program that takes in employee payroll information and then displays the average and total afterwards. Everything seems to be working correctly except for the fact I cannot get the program to end when I enter the sentinel value of -1 for the hours worked so that the program can display the total and average of the employees. Any help is greatly appreciated.
import java.util.Scanner;
public class PayrollDo
{
public static void main(String[] args)
{
int hoursWorked = 0;
int grossPay = 0;
int empCounter = 0;
int total = 0;
Scanner keyboard = new Scanner(System.in);
do {
total = total + grossPay; // add gross to total
empCounter = empCounter + 1; // incriment counter
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
System.out.print("Enter hourly wage: ");
int hourlyWage = keyboard.nextInt();
//System.out.println("Grosspay is " + (hourlyWage * hoursWorked));
keyboard.nextLine();
System.out.println("Enter employee name ");
String name = keyboard.nextLine();
} while(hoursWorked != -1);
// if user entered at least one employee
if (empCounter != 0) {
// use number with decimal point to calculate average of employees
int average = (int) total / empCounter;
// display total and average (with two digits of precision)
System.out.printf("%nTotal of the %d employees entered is %d%n",
empCounter, total);
System.out.printf("Employee average is " + average);
}
else {
// no employees were entered, so output appropriate message
System.out.println("No employees were entered");
}
}
}
Test soon after entering the value whether it is -1 or not
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
if (hoursWorked == -1) break;
edit
I think you will also have trouble with Integer division http://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0
You could restructure your do loop to put the hoursWorked input last (otherwise you have to complete the entries) - and also, add a conditional to reject all entries that cycle, otherwise empCounter is off by one. And I think the total calculation needs reworking too:
do {
System.out.println("Enter employee name ");
String name = keyboard.nextLine();
System.out.print("Enter hourly wage: ");
int hourlyWage = keyboard.nextInt();
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
keyboard.nextLine();
if (hoursWorked != -1) {
total = total + (hourlyWage * hoursWorked); //
empCounter = empCounter + 1; // incriment counter
}
} while(hoursWorked != -1);
In cases like this it can be simpler to have a question like "More Employees? (y/n)" that is used to terminate the loop, using a boolean flag as the while terminator.
Current i am scanning in 4 exam score grades, each to their own variable that has been declared and initialized. I was wondering if there was better way i should be doing this to make it less clutters. Please bear with me though as i am currently in my first java class at uni and dont have any prior experience so i dont want the solution to be super complex, not yet at least but something easily understandable. Not sure if it helps/matters but i am using BlueJ as my IDE.
import java.util.*;
public class GradeCalculatorDriver
{
public static void main(String [] args){
String s1 = "student";//Declare student string variable;
String s2;
double exam1 = 0;//Declare and initalize variables.
double exam2 = 0;//Declare and initalize variables.
double exam3 = 0;//Declare and initalize variables.
double exam4 = 0;//Declare and initalize variables.
do{
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of 4 exam scores, and return the lowest, highest, and letter grade associated with the average");
System.out.println("Please enter the name of the student");//Request student name and scans it into a string.
String student = input.next();
System.out.println("Please enter one exam score, then hit enter and repeat for following grades.");//Request exam scores and scan them into variables.
exam1 = input.nextDouble();
exam2 = input.nextDouble();
exam3 = input.nextDouble();
exam4 = input.nextDouble();
double highest = GradeCalculator.high(exam1, exam2, exam3, exam4);//Calls highest grade method.
double lowest = GradeCalculator.low(exam1, exam2, exam3, exam4);//Calls lowest grade method.
double average = GradeCalculator.avg(exam1, exam2, exam3, exam4);//Calls average grade method.
char letterGrade = GradeCalculator.letter(exam1, exam2, exam3, exam4);//Calls letter grade method.
System.out.printf("The highest exam score is : %.2f " + highest);//Displays highest grade.
System.out.printf("The lowest exam score is : %.2f " + lowest);//Displays lowest grade.
System.out.printf("The average exam score is : %.2f " + average);//Displays average grade.
System.out.print("The letter grade is " + letterGrade);//Displays letter grade associated with average.
System.out.println("Would you like to enter another students grades? (yes/no)");//asks the user if they would like to calculate another factorial.
s2 = input.next();
} while (s2.equalsIgnoreCase("YES"));//checks to see what the users response was.
System.out.print("Thank you for using my program!");//Ending statement.
}
}
public class GradeCalculator{
public static double high(double exam1, double exam2, double exam3, double exam4){//Calculates the highest exam score entered.
double highest;//Declare and initilize variable.
highest = Math.max(Math.max(Math.max(exam1, exam2), exam3), exam4);
return highest;//Returns highest exam score.
}
public static double low(double exam1, double exam2, double exam3, double exam4){//Calculates the lowest exam score entered.
double lowest = 0;//Declare and initilize variable.
lowest = Math.min(Math.min(Math.min(exam1, exam2), exam3), exam4);
return lowest;//Returns highest exam score.
}
public static double avg (double exam1, double exam2, double exam3, double exam4){//Calculates the average exam score.
double average;//Declare variable.
double count = 4;//Declare and initilize variable.
average = ((exam1 + exam2 + exam3 + exam4) / count);
return average;//Returns average grade.
}
public static char letter (double exam1, double exam2, double exam3, double exam4){//Calculates the letterGrade based on the average exam score.
char letterGrade;//Declare and initilize variable.
double count = 4;//Declare and initilize variable.
double average = ((exam1 + exam2 + exam3 + exam4) / count);//declare and calculate average score.
if (average >= 90)
letterGrade = 'A';
else if (average >= 80)
letterGrade = 'B';
else if (average >= 70)
letterGrade = 'C';
else if (average >= 60)
letterGrade = 'D';
else
letterGrade = 'E';
return letterGrade;//Returns letter grade.
}
}
You can use a List<Double> scores = new ArrayList<>() to hold the exam score values and reduce code clutter. Then as you added new exam scores from user input, you would call scores.add(input.nextDouble()) for each input value.
Well, in my opinion, if this is your first kick at the cat (so to speak) then you're well on your way to being a successful Java programmer. As for reducing clutter, I suppose it depends upon what you have already learned, like the Java methods and statements already covered and are now at your disposal to create an application to accomplish the task at hand. There is really no way to know the extent of your learning and therefore the suggestions provided below should only be defined as mere suggestions:
There is nothing wrong with your current model other than a few minor errors which will generate a MissingFormatArgumentException and that is within the code lines:
System.out.printf("The highest exam score is : %.2f " + highest);
System.out.printf("The lowest exam score is : %.2f " + lowest);
System.out.printf("The average exam score is : %.2f " + average);
Any errors within your code should be repaired first. Each of the code lines above contains a fault and it's simply because there is no argument supplied for the format specifier (%.2f). This is because you placed a plus (+) character in place of where a comma separator character is to go so as to indicate the argument for %.2f to represent. In this case the + will append the following string or variable content to the string before it. The code should be:
System.out.printf("The highest exam score is : %.2f ", highest);
System.out.printf("The lowest exam score is : %.2f ", lowest);
System.out.printf("The average exam score is : %.2f ", average);
Or just utilize the String.format() method:
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
Declaring Scanner should not be done upon every iteration of your do/while loop. Place this declaration above the do/while code block so as not to open unnecessary instances of Scanner.
Explaining application functionality does not need to be done upon each iteration of the do/while loop. Move this message above the do/while code block.
When prompting for User input don't use the Scanner#next() method unless you are expecting to receive string tokens. Sometimes it's just plain easier to use the Scanner#nextLine() method. In my opinion I feel it can give more flexibility and allows you a better opportunity to prevent possible exceptions (don't rely on exceptions if you can prevent them).
Believe it or not...sometimes comments can be the biggest source of code clutter. There is absolutely no need to comment the obvious. Yes, I might have done so but it's only so as to explain the code. It is expected to be deleted.
You can get rid of the code line: String s1 = "student";//Declare student string variable;. You don't seem to use this variable anywhere.
As already suggested an array or collection mechanism can be used to hold student scores however in the sense of reducing clutter, it won't for a mere 4 scores but it will for many more scores and therefore is a good way to handle this portion of the code. It is still a good way to go in any case if your course has already covered the use of Arrays and or ArrayLists. Not sure if your requirements are to utilize only what you've already learned. In any case....
To utilize an array to store Student scores you would also need to modify all your methods within the GradeCalculator Class. This in itself will remove parameter clutter since all you would need is a single parameter instead of 4 for each method. The methods in that class might look something like this if you want to use Arrays:
public class GradeCalculator {
public static double high(double[] exams) {//Calculates the highest exam score entered.
double highest = 0.0d;//Declare and initilize variable to 0.0
for (int i = 0; i < exams.length; i++) {
if (exams[i] > highest) {
highest = exams[i];
}
}
return highest;//Returns highest exam score.
}
public static double low(double[] exams) {//Calculates the lowest exam score entered.
double lowest = exams[0];
for (int i = 0; i < exams.length; i++) {
if (exams[i] < lowest) {
lowest = exams[i];
}
}
return lowest;//Returns lowest exam score.
}
public static double avg(double[] exams) {//Calculates the average exam score.
double average = 0.0d; //Declare variable.
double sum = 0.0d;
for (int i = 0; i < exams.length; i++) {
sum+= exams[i];
}
average = sum / exams.length;
return average; //Returns average grade.
}
//Calculates the letter-Grade based on the average exam score.
public static char letter(double average) {
char letterGrade;//Declare and initilize variable.
if (average >= 90) {
letterGrade = 'A';
}
else if (average >= 80) {
letterGrade = 'B';
}
else if (average >= 70) {
letterGrade = 'C';
}
else if (average >= 60) {
letterGrade = 'D';
}
else {
letterGrade = 'E';
}
return letterGrade; //Returns letter grade.
}
}
The letter() method only ever needed one parameter instead of the 4 you had forced to provide and that is the value that is returned from the average() method. You see, you don't need to calculate the average again within the letter() method since you already have a method that does, and has done that. Just pass the already calculated average to the letter() method.
To fill an array with User input it's best to carry out the task using a loop of some sort but then again, it depends upon exactly how you want the User to provide that information (like Test Scores). Perhaps you would like the User to supply all the scores from a single input by separating each score with a white-space:
Please enter all student scores (separated with a space):
65 112 75 88
The code for this might look something like this:
String s2;
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; // Declare Array
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
+ LS + "desired exam scores and return the lowest, highest, and "
+ LS + "letter grade associated with that determined average." + LS);
do {
s2 = "";
invalidEntry = false;
// Request Student Name
System.out.println("Please enter the name of the student (nothing to exit):");
String student = input.nextLine();
if (student.equals("")) { break; }
// Request exam scores
System.out.println("Please enter all student scores (each separated with a space): ");
String scores = input.nextLine();
// If nothing was supplied break out of loop
if (scores.equals("")) {
invalidEntry = true;
break;
}
String[] scoresArray = scores.split("\\s+"); // Split the input into single scores (regex "\\s+" is used to split on one or more whitespaces).
exams = new double[scoresArray.length]; // Initalize Array.
// Convert scores to double data type...
for (int i = 0; i < scoresArray.length; i++) {
/* Is the string value actually a numerical signed
or unsigned integer or double type value. Save
this Regular Expression. It's handy to have. */
if (scoresArray[i].matches("-?\\d+(\\.\\d+)?")) {
exams[i] = Double.parseDouble(scoresArray[i]);
}
else {
System.out.println("One or more of the Scores supplied are invalid! "
+ "Enter Student Scores again!" + LS);
invalidEntry = true;
break;
}
}
if (invalidEntry) { continue; } // Redo loop on Invalid Entry
double highest = high(exams);
double lowest = low(exams);
double average = avg(exams);
char letterGrade = letter(average);
System.out.println(LS + "Results For Student: " + student);
System.out.println("From " + String.format("%02d" , exams.length) +
" exam scores: " +
Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
System.out.println("The letter grade is: " + letterGrade + LS);
while (s2.equals("")) {
System.out.println("Would you like to enter another Students Scores? (yes/no)");
s2 = input.nextLine();
if (!s2.equalsIgnoreCase("yes") && !s2.equalsIgnoreCase("no")) {
System.out.println("Invalid Response! 'Yes' or 'No' only!");
s2 = "";
}
}
} while (s2.equalsIgnoreCase("yes") || invalidEntry);
System.out.println("Thank you for using my program!");
Sometimes it is just easier for the User to enter all the scores on one line as demonstrated within the above code however, you set the rules towards how your application is to function. If you want each score to be entered individually then so be it. The code might then look something like this:
String s2;
int indexCounter; // Declare an index counter for array.
boolean invalidEntry;
String LS = System.lineSeparator();
double[] exams; //Declare Array.
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the average of any number of "
+ LS + "desired exam scores and return the lowest, highest, and "
+ LS + "letter grade associated with that determined average." + LS);
do {
s2 = "";
indexCounter = 0; // Set index counter to 0
invalidEntry = false;
// Request Student Name
System.out.println("Please enter the name of the Student (nothing to exit):");
String student = input.nextLine();
if (student.equals("")) { break; }
// Get number of Scores to enter from User
int numberOfScores = 0;
while (numberOfScores == 0) {
System.out.println("Please enter the number of scores you wish to enter:");
String numScores = input.nextLine();
// Is the value supplied a String Integer value
if (!numScores.matches("\\d+")) {
System.out.println("Invalid number of scores provided! Try Again..." + LS);
continue;
}
numberOfScores = Integer.parseInt(numScores);
}
exams = new double[numberOfScores]; // Initialize Array
// Request exam scores
while (indexCounter < numberOfScores) {
System.out.println("Please enter exam score #" + (indexCounter + 1) +
" then hit enter: ");
exams[indexCounter] = input.nextDouble();
input.nextLine(); // Clear the scanner buffer
indexCounter++;
}
double highest = high(exams);
double lowest = low(exams);
double average = avg(exams);
char letterGrade = letter(average);
System.out.println(LS + "Results For Student: " + student);
System.out.println("From " + String.format("%02d" , exams.length) +
" exam scores: " +
Arrays.toString(exams).replaceAll("[\\[\\]]", ""));
System.out.println("The lowest exam score is: " + String.format("%.2f",lowest));
System.out.println("The highest exam score is: " + String.format("%.2f", highest));
System.out.println("The average exam score is: " + String.format("%.2f", average));
System.out.println("The letter grade is: " + letterGrade + LS);
while (s2.equals("")) {
System.out.println("Would you like to enter another Student's Scores? (yes/no)");
s2 = input.nextLine();
if (!s2.equalsIgnoreCase("YES") && !s2.equalsIgnoreCase("NO")) {
System.out.println("Invalid Response! 'Yes' or 'No' only!");
s2 = "";
}
}
} while (s2.equalsIgnoreCase("YES") || invalidEntry);
System.out.println("Thank you for using my program!");
You will have noticed that some of the code above takes advantage of Regular Expressions such as "\\s+", "\\d+", "[\\[\\]]", or even "-?\\d+(\\.\\d+)?". It's never to late to learn how to utilize Java's java.util.regex package for pattern matching. It can quickly become a close friend for you and once learned, you will find yourself using it all the time. To test Regular Expressions and to get explanations of what a particular expression does you can use the website RegEx101.com for example: this regex.
I have two programs:
Score.java set to do the following:
read scores from the keyboard and print their average.
The scores will be numeric and may include a decimal part.
For example a score might be 8.73 or some such. Different contests will have different numbers of judges. It will keep asking for and reading in scores until the user types 'done'. The program will then print the total score, the number of scores and the average score. The program will then prompt the user to see if there are any more contestants. If there are begin prompting for scores again. If there are no more then exit the program." I have it set to stop the program when you enter "N", and set to add future entries to the calculation after entering "Y".
import java.util.Scanner;
// This is the Score program
// Written by me
public class Score
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = sum + num;
cnt = cnt + 1;
System.out.print("enter number: ");
ans = game.next();
}
System.out.println(cnt);
System.out.println(sum);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
While the above process works, I cannot get my second program, Olympic.java, to work properly after typing "Y" to add more scores. Instead, it starts a whole new calculation of average instead of adding to the previous calculations:
import java.util.Scanner;
// This is the Olympic program
// Written by me
public class Olympic
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
double highscore = Double.MAX_VALUE;
double lowscore = Double.MIN_VALUE;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
lowscore = game.nextDouble();
highscore = game.nextDouble();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = (sum + num) - lowscore - highscore;
cnt = cnt + 1;
System.out.print("enter number: ");
if (num > highscore)
{
highscore = num;
}
if (num < lowscore)
{
lowscore = num;
}
ans = game.next();
}
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
So I did a really quick test
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
while (true) {
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equalsIgnoreCase("Y")) {
break;
}
}
System.out.println("I'm free");
}
And this will exit fine.
As to your second problem. I think your logic is a little skewed. You could try something like...
Scanner game = new Scanner(System.in);
double num = 0;
double sum = 0;
int cnt = 0;
while (true) {
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
double lowscore = Double.MAX_VALUE;
double highscore = 0;
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done")) {
num = Double.parseDouble(ans);
lowscore = Math.min(lowscore, num);
highscore = Math.max(highscore, num);
sum += num;
cnt++;
System.out.print("enter number: ");
if (num > highscore) {
highscore = num;
}
if (num < lowscore) {
lowscore = num;
}
ans = game.next();
}
sum -= lowscore;
sum -= highscore;
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equalsIgnoreCase("Y")) {
break;
}
}
This will output...
Enter as many non-negative integers as you like
one at a time and I will find the average
Enter done to stop entering numbers
enter number: 1
enter number: 2
enter number: 3
enter number: 4
enter number: 5
enter number: 6
enter number: 7
enter number: 8
enter number: 9
enter number: 10
enter number: done
Throwing out low score 1.0 and high score 10.0
Total Score 44.0 count scores 10 avg score 4.4
Enter another contestant (Y/N)?
y
Enter as many non-negative integers as you like
one at a time and I will find the average
Enter done to stop entering numbers
enter number: 1
enter number: 12
enter number: 13
enter number: 14
enter number: 15
enter number: 16
enter number: 17
enter number: 18
enter number: 19
enter number: 20
enter number: done
Throwing out low score 1.0 and high score 20.0
Total Score 168.0 count scores 20 avg score 8.4
Enter another contestant (Y/N)?
n
As to your exception. When using Scanner.nextDouble, it will throw an exception if the input is not parsable as a double. You will need to deal with this situation as you see fit...