I am having an issue getting the sum of the integers in my array AND an issue getting the product of an integer * 1.5. My code below could be completely off as I am new to Java and have been at this for hours and hours. The purpose of the program is to enter the number of hours worked, each day, for 5 days. With that, and the pay rate, you're supposed to output the average hours worked, total hours, and total pay. The pay should also include overtime if there is any. Any help would be appreciated.
String name;
String id;
int payRate;
int[] hours = new int[5];
int avgHours;
int totalPay;
int totalHours = 0;
int counter;
int overTime = 0;
//housekeeping
System.out.print("Enter the Employee's name: ");
inputString = input.readLine();
name = inputString;
System.out.print("Enter the Employee's ID: ");
inputString = input.readLine();
id = inputString;
System.out.print("Enter the Employee's pay rate: ");
inputString = input.readLine();
payRate = Integer.parseInt(inputString);
//hoursPay
counter = 0;
for(hours[counter] = 0; counter < 5; counter++)
{
System.out.print("How many hours did the employee work? ");
inputString = input.readLine();
hours[counter] = Integer.parseInt(inputString);
}//endfor
for(totalHours = 0; counter < 5; hours[counter]++);
{
totalHours += hours[counter];
if(totalHours > 40)
{
overTime = payRate + (payRate / 2);
}//endif
}//endwhile
//print
if(counter == 5)
{
System.out.println(name + " " + id + " $" + payRate + "/hour" );
avgHours = totalHours / counter;
totalPay = totalHours * payRate + overTime;
System.out.println...
System.out.println...
System.out.println...
#bp_1,
I re-do all the code again and pasted it below. It WORKS. There was some fundamental error you making while coding. Compare your code with mine and you will see the difference.
String name;
String id;
int payRate;
int[] hours = new int[5];
int avgHours;
int totalPay;
int totalHours = 0;
int counter;
int overTime = 0;
Scanner input = new Scanner(System.in);
//housekeeping
System.out.print("Enter the Employee's name: ");
String inputString = input.nextLine();
name = inputString;
System.out.print("Enter the Employee's ID: ");
inputString = input.nextLine();
id = inputString;
System.out.print("Enter the Employee's pay rate: ");
inputString = input.nextLine();
payRate = Integer.parseInt(inputString);
//hoursPay
counter = 0;
for (hours[counter] = 0; counter < 5; counter++) {
System.out.print("How many hours did the employee work? ");
inputString = input.nextLine();
hours[counter] = Integer.parseInt(inputString);
}//endfor
counter = 0;// reset counter here
for (totalHours = 0; counter < 5; counter++) {
totalHours += hours[counter];
if (totalHours > 40) {
overTime = payRate + (payRate / 2);
}//endif
}//end of for loop
if (counter == 5) {
System.out.println(name + " " + id + " $" + payRate + "/hour");
avgHours = totalHours / counter;
totalPay = totalHours * payRate + overTime;
System.out.println("Average Hours: " + avgHours);
System.out.println("Total pay: " + totalPay);
System.out.println("Total Hours: " + totalHours);
System.out.println("Overtime ($): " + overTime);
}//end of if
In place of
for(totalHours = 0; counter < 5; hours[counter]++);
write
for(counter = 0; counter < 5; counter++)
semicolon removed.
counter incremented instead of hours[counter]
Related
I am trying to build a string, and put the result of the loop
"att" into string with the index "i". So, I can sort the string and output the highest attendance school with the school number. Thanks!
import java.util.Scanner;
public class PengjuShanP1 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many schools do you have in your district: ");
int nos = scnr.nextInt();
int[] nums = new int[nos];
System.out.println();
double ax = 0;
for (int i = 1; i < nos + 1; ++i) {
System.out.println("Enter data for school " + i);
System.out.print(" How many students are enrolled in school : ");
int num = scnr.nextInt();
System.out.print(" Enter the attendance for day 1: ");
int d1 = scnr.nextInt();
System.out.print(" Enter the attendance for day 2: ");
int d2 = scnr.nextInt();
System.out.print(" Enter the attendance for day 3: ");
int d3 = scnr.nextInt();
System.out.print(" Enter the attendance for day 4: ");
int d4 = scnr.nextInt();
System.out.print(" Enter the attendance for day 5: ");
int d5 = scnr.nextInt();
double avg = ((d1 + d2 + d3 + d4 + d5) / 5) * 100;
double att = avg / num;
ax = att + ax;
System.out.println();
System.out.println("Attendance " + att + "% for school " + i);
System.out.println();
}
System.out.print(ax);
}
}
EDIT
Given that the school id is an integer, it's possible to do this in a simple array, which is more space and time efficient than the collections API below.
Initialize a double array early on:
double[] schools = new double[nos];
Add data in the loop:
schools[i] = att;
And find the highest at the end, with printing:
double highest = 0;
int index = 0;
for (int i = 0; i < schools.length; i++)
{
if (schools[i] > highest)
{
index = i;
highest = schools[i];
}
}
System.out.println("The school with the best attendance is school " + (index + 1) + " with " + highest + "% attendance");
The full example:
import java.util.Scanner;
public class ValuePairSortingSimpler
{
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
System.out.print("How many schools do you have in your district: ");
int nos = scnr.nextInt();
double[] schools = new double[nos];
System.out.println();
double ax = 0;
for (int i = 0; i < nos; i++)
{
System.out.println("Enter data for school " + (i + 1));
System.out.print(" How many students are enrolled in school : ");
int num = scnr.nextInt();
System.out.print(" Enter the attendance for day 1: ");
int d1 = scnr.nextInt();
System.out.print(" Enter the attendance for day 2: ");
int d2 = scnr.nextInt();
System.out.print(" Enter the attendance for day 3: ");
int d3 = scnr.nextInt();
System.out.print(" Enter the attendance for day 4: ");
int d4 = scnr.nextInt();
System.out.print(" Enter the attendance for day 5: ");
int d5 = scnr.nextInt();
double avg = ((d1 + d2 + d3 + d4 + d5) / 5) * 100;
double att = avg / num;
schools[i] = att;
ax = att + ax;
System.out.println();
System.out.println("Attendance " + att + "% for school " + (i + 1));
System.out.println();
}
double highest = 0;
int index = 0;
for (int i = 0; i < schools.length; i++)
{
if (schools[i] > highest)
{
index = i;
highest = schools[i];
}
}
System.out.println("The school with the best attendance is school " + (index + 1) + " with " + highest + "% attendance");
System.out.print(ax);
}
}
Original Post:
I'm not sure a string is the best route here. If I'm not mistaken, you'd like to store several pairs of values in a list or array and then sort that by one of the values. That problem is best solved using the collections API. For an example:
Define a list of key-value pairs at the beginning (before the loop). The key will be the school id and the value will be the attendance.
List<Map.Entry<Integer, Double>> schools = new ArrayList<>();
Then add the data to the list in the loop:
schools.add(Map.entry(i, att));
And at the end, sort it descending by value (highest first), then print the results.
schools.sort((a,b)->(int)Math.round(b.getValue()-a.getValue()));
System.out.println("The school with best attendance is school " + schools.get(0).getKey() + " with " + schools.get(0).getValue() + "% attendance!");
A full example follows:
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
System.out.print("How many schools do you have in your district: ");
int nos = scnr.nextInt();
List<Map.Entry<Integer, Double>> schools = new ArrayList<>();
System.out.println();
double ax = 0;
for (int i = 1; i < nos + 1; ++i)
{
System.out.println("Enter data for school " + i);
System.out.print(" How many students are enrolled in school : ");
int num = scnr.nextInt();
System.out.print(" Enter the attendance for day 1: ");
int d1 = scnr.nextInt();
System.out.print(" Enter the attendance for day 2: ");
int d2 = scnr.nextInt();
System.out.print(" Enter the attendance for day 3: ");
int d3 = scnr.nextInt();
System.out.print(" Enter the attendance for day 4: ");
int d4 = scnr.nextInt();
System.out.print(" Enter the attendance for day 5: ");
int d5 = scnr.nextInt();
double avg = ((d1 + d2 + d3 + d4 + d5) / 5) * 100;
double att = avg / num;
schools.add(Map.entry(i, att));
ax = att + ax;
System.out.println();
System.out.println("Attendance " + att + "% for school " + i);
System.out.println();
}
System.out.print(ax);
schools.sort((a,b)->(int)Math.round(b.getValue()-a.getValue()));
System.out.println("The school with best attendance is school " + schools.get(0).getKey() + " with " + schools.get(0).getValue() + "% attendance!");
}
The question is not clear and array index always start from zero instead of 1 as mentioned in the for loop. if you are looking to store att in array of String, declare String array and store att in the string array
I have to create a program to calculate the average of each students' scores. I managed to do that but how can I limit the score to be only between 0 to 100? I've searched other questions and many shows to put while statement. The problem is that I don't know where to add the while. So here's the code:
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
If there is any other ways please do state. Thanks in advance.
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}
//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}
Valid = false; //reset validation;
Total += Input;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid:
Scanner scanner = new Scanner(System.in);
int score;
while (true) {
System.out.print("Please enter score " + (g + 1) + ": ");
score = scanner.nextInt();
if (score >= 0 && score <= 100) {
break;
}
System.out.println("Please enter a valid score between 0 and 100!");
}
Total += score;
Remember to close your Scanners to avoid memory leaks!
I'm having a problem with this Java code. It's a questionnaire that should calculate your grade. It all goes and runs well until the very last part where it says "current score" that whole equation should equal 33.16 but instead it equals 24.
I changed some values, did some research but I haven't found what I'm looking for.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
System.out.println("Grading Scale:");
System.out.println("A\t 90 - 100");
System.out.println("B\t 80 - 89");
System.out.println("C\t 70 - 79");
System.out.println("D\t 60 - 69");
System.out.println("F\t below 60");
System.out.println("What letter grade do you want to achieve for the course?");
String desiredGrade;
Scanner keyboard = new Scanner(System.in);
desiredGrade = keyboard.next();
if (desiredGrade.equalsIgnoreCase("A") || desiredGrade.equalsIgnoreCase("B")
|| desiredGrade.equalsIgnoreCase("C") || desiredGrade.equalsIgnoreCase("D")
|| desiredGrade.equalsIgnoreCase("F")) {// is this necessary? vv
System.out.println("Enter Percentage Weights");
}
else {
System.out.println("Input error.");
System.exit(0);
}
int exam1, exam2, finalExam, labs, projects, attendance, quizzes;
System.out.println("Exam 1:\t");
exam1 = keyboard.nextInt();
System.out.println("Exam 2:\t");
exam2 = keyboard.nextInt();
System.out.println("Final Exam:\t");
finalExam = keyboard.nextInt();
System.out.println("Labs:\t");
labs = keyboard.nextInt();
System.out.println("Projects:\t");
projects = keyboard.nextInt();
System.out.println("Attendance:\t");
attendance = keyboard.nextInt();
System.out.println("Quizzes:\t");
quizzes = keyboard.nextInt();
// so the semicolon isn't needed after the if statement?
if (exam1 + exam2 + finalExam + labs + projects + attendance + quizzes != 100) {
System.out.println("Weights don't add up to 100, program exiting");
System.exit(0);
}
System.out.println("Enter your scores out of a 100:");
System.out.println("Do you know your Exam 1 score?");
String answer;
int exam1score = 0, exam2score = 0, finalExamScore = 0, labAverage = 0, projectAverage = 0, quizAverage = 0, attendanceAverage = 0;
double currentScore = 0;
answer = keyboard.next();
// ask about this
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
// why can't i put int here?
System.out.println("Score received on exam 1:");
exam1score = keyboard.nextInt();
System.out.println("Do you know your Exam 2 score?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on exam 2:");
exam2score = keyboard.nextInt();
System.out.println("Do you know your Final Exam score?");
answer = keyboard.next();
}
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on final exam");
finalExamScore = keyboard.nextInt();
}
}
System.out.println("Do you know your lab average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Lab Grade:");
labAverage = keyboard.nextInt();
}
System.out.println("Do you know your project average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Project Grade:");
projectAverage = keyboard.nextInt();
}
System.out.println("Do you know your quiz average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Quiz Grade:");
quizAverage = keyboard.nextInt();
}
System.out.println("Do you know your attendance average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Attendance Grade:");
attendanceAverage = keyboard.nextInt();
}
currentScore = ((double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage)/((double)exam1+exam2+finalExam+labs+projects+attendance+quizzes);
System.out.println("Current Grade Score:\t " + currentScore);
String grade;
if (currentScore >= 90)
grade = "A";
else if (currentScore >= 80)
grade = "B";
else if (currentScore >= 70)
grade = "C";
else if (currentScore >= 60)
grade = "D";
else
grade = "F";
}
}
The following only converts the exam1score*exam1 value to double, not the entire expression.
(double) exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore + ....
So, you should do something like this.
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage;
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (double) nominator / denominator;
OR
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage);
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (nominator * 1.0) / denominator;
(double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage
only converts the first one to double and leaves the rest as int.
So I'm writing a program for an invoice calculator for class.
However, I need to code interest for every 30 days for 10%
total * interest rate (0.10) if 30 days
So, lets say they need to pay interest for 60 days. so twice
total * interest rate --> with another interest on top of that and so on
another example:
so for the program it depends on the date since last invoice. if it is 30 daysyou will be charged 10% interest. if it is 60 days you will be charged another 10% interest on top of that. if it is 90 days you will be charged another 10% interest on top of that. and so on
Do I use a for loop?
public static void main(String[] args) {
// TODO Auto-generated method stub
DecimalFormat formatter = new DecimalFormat("#0.00");
Scanner input = new Scanner (System.in);
double purchase, invoiceAmount, tax, interest, total = 0;
int validYear, validMonth, validDay, invoiceYear, invoiceMonth, invoiceDay;
int daysdiff;
/* double invoiceAmount = 0;
double tax = 0;
double total = 0;*/
System.out.println("Welcome to the Invoice Calculator\n");
System.out.print("Enter the number of minutes you wish to purchase: ");
purchase = input.nextDouble();
System.out.println("Today's Date");
System.out.print ("Year: ");
validYear = input.nextInt ();
while(validYear < 1950 || validYear > 2016){
System.out.print ("Invalid!!\nEnter Year: " );
validYear = input.nextInt();
}
System.out.print ("Month: ");
validMonth = input.nextInt ();
while(validMonth < 1 || validMonth > 12){
System.out.print ("Invalid!!\nEnter Month: " );
validMonth = input.nextInt();
}
System.out.print ("Day: ");
validDay = input.nextInt ();
while(validDay < 1 || validDay > 30){
System.out.print ("Invalid!!\nEnter day: " );
validDay = input.nextInt();
}
System.out.println("Invoice Date");
System.out.print ("Year: ");
invoiceYear = input.nextInt ();
while(validYear < 1950 || validYear > 2016){
System.out.print ("Invalid!!\nEnter year " );
invoiceYear = input.nextInt();
}
System.out.print ("Month: ");
invoiceMonth = input.nextInt ();
while(invoiceMonth < 1 || invoiceMonth > 12){
System.out.print ("Invalid!!\nEnter month: " );
invoiceMonth = input.nextInt();
}
System.out.print ("Day: ");
invoiceDay = input.nextInt ();
while(invoiceDay < 1 || invoiceDay > 30){
System.out.print ("Invalid!!\nEnter day: " );
invoiceDay = input.nextInt();
}
System.out.println("\nToday's Date is: " + validYear + "/" + validMonth + "/" + validDay);
System.out.println("Invoice Date is: " + invoiceYear + "/" + invoiceMonth + "/" + invoiceDay + "\n");
invoiceAmount = (purchase * 0.02) +5;
tax = (invoiceAmount * 0.13);
total = (invoiceAmount + tax);
interest = (total * 0.10);
// The number of days since invoice date:
daysdiff = (validYear - invoiceYear) *365 + (validMonth - invoiceMonth) *30 +(validDay - invoiceDay);
System.out.print("The number of days since invoice date is: " + daysdiff);
System.out.print("\nInvoice Amount: $");
System.out.println(formatter.format(invoiceAmount));
System.out.print("Tax : $");
System.out.println(formatter.format(tax));
System.out.print("Interest : $");
System.out.println(formatter.format(interest));
System.out.print("TOTAL : $");
System.out.println(formatter.format(total));
}
}
Thank you
if you want to tax 10% for every 30days you'd need something like this.
public class test {
public static void main(String[] args) {
double total = 100.0;
int numDays = 90;
//gets how many times your invoice days goes into 30
int taxNum = numDays / 30;
//decreases total according to your tax
for( int i = 0; i < taxNum; i++ ){
total -= total * .1;
}
System.out.println(total);
}
}
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();