I can't get the while loop to work. The Program prompt user whether (s)he wants to continue, enter 0 toquit or any other integer to continue. If the user wants to c
ontinue, the program will loop back to themenu, otherwise, it will exit. Thus, you should have a sentinel-controlled loop that will end when a 0 is entered
import java.util.Scanner;
public class AdoptAPet
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int gender = 0;
double costAdoption = 0.0;
double costGenderSelect = 0.0;
double costAnyGender = 0.0;
double costProcessing = 0.0;
double total = 0.0;
int genderCounter = 0;
System.out.println("Choose from the following options: 1 for male, 2 for female, 3 for any");
while(gender != 0);//begin sentinel controlled while loop
{
System.out.print("Please choose the gender of the cat you wish to purchase:");
gender = input.nextInt();
if(gender < 0)
{
System.out.println("INVALID CHOICE! ");
System.out.print("enter 0 to quit: 0 or enter any other nunber to continue:");
gender = input.nextInt();
}
if(gender == 1)
{
costAdoption = 9.50;
costAdoption += costProcessing + 2.00;
total += costAdoption;
System.out.printf("Your Choice is: " );
System.out.printf("male and the total is $%.2f", total);
}
if(gender == 2)
{
costGenderSelect = 11.50;
costGenderSelect += costProcessing + 2.00;
total += costGenderSelect;
System.out.printf("Your Choice is: " );
System.out.printf("female and the total is $%.2f", total);
}
if(gender == 3)
{
costAnyGender = 9.50;
costAnyGender += costProcessing + 2.00;
total += costAnyGender;
System.out.printf("Your Choice is: " );
System.out.printf("Any gender and the total is $%.2f", total);
}
}
}
}
This line is responsible:
while(gender != 0);//begin sentinel controlled while loop
Look closely. There is a semi-colon at the end - that is the entire statement. The {} block that follows does not belong to the loop (and is executed exactly once).
Try dropping the ; from the end - we've fixed our while loop, but now the {} loop body doesn't execute at all. This is because gender is initialized with a value of 0. So to get our loop to execute at least once we need to either initialize gender to something else, or use a do-while loop.
Here is the modified code using a do-while.
import java.util.Scanner;
public class AdoptAPet
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int gender = 0;
double costAdoption = 0.0;
double costGenderSelect = 0.0;
double costAnyGender = 0.0;
double costProcessing = 0.0;
double total = 0.0;
int genderCounter = 0;
System.out.println("Choose from the following options: 1 for male, 2 for female, 3 for any");
do //begin sentinel controlled while loop
{
System.out.print("Please choose the gender of the cat you wish to purchase:");
gender = input.nextInt();
if(gender < 0)
{
System.out.println("INVALID CHOICE! ");
System.out.print("enter 0 to quit: 0 or enter any other nunber to continue:");
gender = input.nextInt();
}
if (gender == 1)
{
costAdoption = 9.50;
costAdoption += costProcessing + 2.00;
total += costAdoption;
System.out.printf("Your Choice is: " );
System.out.printf("male and the total is $%.2f", total);
}
if (gender == 2)
{
costGenderSelect = 11.50;
costGenderSelect += costProcessing + 2.00;
total += costGenderSelect;
System.out.printf("Your Choice is: " );
System.out.printf("female and the total is $%.2f", total);
}
if (gender == 3)
{
costAnyGender = 9.50;
costAnyGender += costProcessing + 2.00;
total += costAnyGender;
System.out.printf("Your Choice is: " );
System.out.printf("Any gender and the total is $%.2f", total);
}
} while(gender != 0); //end sentinel controlled while loop
}
}
Try this:
while(gender != 0);//<-- remove the semi colon,loop gets terminated by it
Also declare gender as:
int gender = -1;//<-- this will cause the loop to start
Related
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!
The amount of investment must be positive and can be any value.
The period of investment is in years so should be positive.
The annual rate of interest can be between 0.25% to 14%.
import java.util.Scanner;
public class InterestCalculator{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
// Entering the interest rate
System.out.print("Please Enter the annual interest rate between 0.25 to 10 : ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = annualInterestRate / 1200;
System.out.print("Enter number of years: ");
int numberOfYears = input.nextInt();
// Entering the amount earned
System.out.print("Enter Amount: ");
double Amountofinterest = input.nextDouble();
// Calculating
double moneyearned = Amountofinterest * monthlyInterestRate;
// Displaying the results
System.out.println("The money earned is $" +
(int) (moneyearned * 100) / 100.0);
int i;
for (i = 1; i <= numberOfYears * 12; i++) {
double Balance = Amountofinterest + moneyearned;
Amountofinterest = Balance;
monthlyInterestRate = moneyearned + 0.01;
System.out.println(i + "\t\t" + Amountofinterest
+ "\t\t" + monthlyInterestRate + "\t\t" + Balance);
}
}
}
I have made the basic program but, I don't know how to add restrictions.
Are you talking about this :
while(input.nextDouble()<0){
System.out.println("Please enter positive investment");
}
You can use loops that repeatedly ask for input until it's valid:
double annualInterestRate = 0;
while (annualInterestRate < 0.25 || annualInterestRate > 10){
System.out.print("Please Enter the annual interest rate between 0.25 to 10 : ");
annualInterestRate = input.nextDouble();
if (annualInterestRate < 0.25 || annualInterestRate > 10){
System.out.println("Please enter a value between 0.25 and 10");
}
}
//if you reach this point, input is valid because it is neither <0.25 or >10
You can do this for all values that need to meet certain criteria. Just make sure you initialize the variable before the loop and set it as an invalid value, otherwise the loop won't run.
Other variables:
int numberOfYears = -1; //or 0 is you don't allow 0 years
while (numberOfYears < 0){ //or <= 0 if you don't allow 0 years
System.out.print("Enter number of years: ");
numberOfYears = input.nextInt();
}
double Amountofinterest = -1; //or 0
while (Amountofinterest < 0){ //or <= 0
System.out.print("Enter Amount: ");
Amountofinterest = input.nextDouble();
}
Ok you could then use a while loop like this:
int numberOfYears = -1;
System.out.print( "Enter number of years: ");
while(numberOfYears < 0){
numberOfYears = input.nextInt();
}
I'd like to offer a more elegant way of getting data via CLI, where the risk of exception or any other input hazard is minimised.
I've written this function and think it may well cover the Integer, Double and String objects, but you may continue expanding it further:
public Object securedInput(String intro, String type, int maxLength)
{
//Apply Scanner
Scanner input = new Scanner(System.in);
//Show intro
if(intro != null)
System.out.print(intro+" ");
//Get user's input
String inStr = input.next(); //always get a string
//Enforce length
if((maxLength>0)&&(inStr.length() > maxLength))
inStr = inStr.substring(0, maxLength);
String result;
if(inStr == null || inStr.length() < 1)
return null;
switch (type)
{
case "int":
result = inStr.replaceAll("[^0-9]", "");
if(result.length() < 1 || result.length() < inStr.length())
return null;
else
return Integer.parseInt(result);
case "double":
result = inStr.replaceAll("[^0-9.]", "");
if(result.length() < 1 || result.length() < inStr.length())
return null;
else
return Double.parseDouble(result);
//break;
case "string":
result = inStr.replaceAll("[^a-zA-Z .-]", "");
if(result.length() < 1 || result.length() < inStr.length())
return null;
else
return result;
default:
return null;
}
}
Here,as you can see I first take the input as String, then clean it according to my need, and then try to convert it without the risk of getting any exception.
And if something is wrong you simply get a null.
This can be used like this:
Integer i = (Integer)securedInput("Enter an integer:","int", 3);
Double d = (Double)securedInput("Enter a double","double",4);
String s = (String)securedInput("Enter a string","string",2);
You can add further arguments, such as range, and forbidden characters and even output errors according to the problem.
Hope this had helped.
I have this, but I'm very lost in how I can get the final GPA to print out, I've tried various ways but have not been able to do it successfully. This is what I have:
Scanner input = new Scanner(System.in);
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
double points = 0.0;
if(gradesArray[i].equalsIgnoreCase("A+") || gradesArray[i].equalsIgnoreCase("A"))
{
points += 4;
}
else if(gradesArray[i].equalsIgnoreCase("A-"))
{
points+= 3.7;
}
else if(gradesArray[i].equalsIgnoreCase("B+"))
{
points += 3.3;
}
else if(gradesArray[i].equalsIgnoreCase("B"))
{
points += 3.0;
}
else if(gradesArray[i].equalsIgnoreCase("B-"))
{
points += 2.7;
}
else if(gradesArray[i].equalsIgnoreCase("C+"))
{
points += 2.3;
}
else if(gradesArray[i].equalsIgnoreCase("C"))
{
points += 2.0;
}
else if(gradesArray[i].equalsIgnoreCase("D"))
{
points += 1.0;
}
else if(gradesArray[i].equalsIgnoreCase("F"))
{
points += 0.0;
}
else
{
System.out.println("Invalid grade");
}
System.out.println("GPA: " + points / gradesArray.length);
}
I'm guessing the GPA does not print out properly because after the condition matches the grade, it then goes right down to print, right? And also, how can I do it so if they enter an invalid grade, it makes the user start over.
You're very close. You need to add another bracket before your println to close out your forloop. You only want to calculate GPA once all of the grades are entered. So like this:
And, as Jason mentioned in the comments, you need to make sure to create points outside of the loop. Otherwise, you won't be able to access it afterwards to get calculate the full GPA.
double points = 0.0; //this has to go out here to be able to access it later
for(int i = 0; i < gradesArray.length; i++) {
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
...
else if(gradesArray[i].equalsIgnoreCase("F")) {
points += 0.0;
} else {
System.out.println("Invalid grade");
}
}
System.out.println("GPA: " + points / gradesArray.length);
As for resetting input, this is easy as well. You can just use a while loop - so do something like this.
boolean inputNeeded = true;
while(inputNeeded) {
System.out.println("Please enter grades:);
String grade = scan.nextLine();
if(grade_is_valid_check_here) {
inputNeeded = false;
} else {
System.out.println("Input is invalid - please try again");
}
}
You could do something similar to this as well. You can use a switch block. points needs to be brought outside the loop or it will just get reset to 0.0 every time a user enters a grade.
To make the user start over if it is an invalid grade you could use a recursive call. This means after the the "Invalid grade" message you would call the method that starts the process over again. This would require a little more refactoring and separating some of this code into more methods.
Scanner input = new Scanner(System.in);
double points = 0.0;
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++){
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
String grade = gradesArray[i].toUpperCase();
switch (gradesArray[i]) {
case "A+":
points += 4;
break;
case "A":
points += 4;
break;
case "A-":
points += 3.7;
break;
case "B+":
points += 3.3;
break;
default:
System.out.println("Invalid grade");
break;
}
}
System.out.println("GPA: " + points / gradesArray.length);
Aside from #Alex K's answer. Not sure if you have learned about HashMaps or not, but you could shorten your code down quite a bit by using them. It also makes it way easier to add another grade and point value with ease.
Scanner input = new Scanner(System. in );
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
String[] gradesArray = new String[length];
//Create a HashMap with String as the key, and a Double as the value
Map < String, Double > grades = new HashMap < > ();
//Insert all the grades and point values
grades.put("A+", 4.0);
grades.put("A-", 3.7);
grades.put("B+", 3.3);
grades.put("B", 3.0);
grades.put("B-", 2.7);
grades.put("C+", 2.3);
grades.put("C", 2.0);
grades.put("D", 1.0);
grades.put("F", 0.0);
double points = 0.0;
for (int i = 0; i < gradesArray.length; i++) {
System.out.println("Enter grade (include + or -) ");
String grade = input.nextLine();
gradesArray[i] = grade;
//If the grades Map contains the inputted grade, use Map.get(grade) to obtain the value and add that to the points Double.
//Otherwise print invalid grade
if (grades.containsKey(grade)) {
points += grades.get(gradesArray[i]);
} else {
System.out.println("Invalid grade");
}
}
System.out.println("GPA: " + points / gradesArray.length);
All you need is declare points as a global variable and print out the GPA outside the for loop
public class Grade {
public static void main(String[] args){
double points=0.0;
Scanner input = new Scanner(System.in);
System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();
String[] gradesArray = new String[length];
for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();
if(gradesArray[i].equalsIgnoreCase("A+") || gradesArray[i].equalsIgnoreCase("A"))
{
points += 4;
}
else if(gradesArray[i].equalsIgnoreCase("A-"))
{
points+= 3.7;
}
else if(gradesArray[i].equalsIgnoreCase("B+"))
{
points += 3.3;
}
else if(gradesArray[i].equalsIgnoreCase("B"))
{
points += 3.0;
}
else if(gradesArray[i].equalsIgnoreCase("B-"))
{
points += 2.7;
}
else if(gradesArray[i].equalsIgnoreCase("C+"))
{
points += 2.3;
}
else if(gradesArray[i].equalsIgnoreCase("C"))
{
points += 2.0;
}
else if(gradesArray[i].equalsIgnoreCase("D"))
{
points += 1.0;
}
else if(gradesArray[i].equalsIgnoreCase("F"))
{
points += 0.0;
}
else
{
System.out.println("Invalid grade");
}
}
System.out.println("GPA: " + points / gradesArray.length);
}
I have a project in mind however there are a few basics I need to master before I can proceed. Here's the issue I'm trying to call a function from main in java but I can't get it to compile. I have read the feedback and I went with using a switch to call each function. I always get "error can't find symbol". I've made a few changes here and there trying to get it to run. Once again I feel like I'm lacking something very fundamental and it's preventing me from getting this to work. Any ideas
import java.util.*;
import java.lang.*;
import java.io.*;
class Practice {
static void wagecalc() {
Scanner input = new Scanner(System.in);
System.out.println("Input pay per hour:");
int a = input.nextInt();
int b;
System.out.println("Input hours worked:");
b = input.nextInt();
int c;
System.out.println("Input days worked:");
c = input.nextInt();
int gross = a * b * c;
System.out.println("Your gross pay is:" + gross);
// Determining tax rate//
if (gross < 10000) {
int taxrate = gross * 10 / 100;
System.out.println("Your tax rate is 10%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross > 10000 || gross <= 30000) {
int taxrate = gross * 15 / 100;
System.out.println("Your tax rate is 15%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross >= 30000 || gross <= 70000) {
int taxrate = gross * 20 / 100;
System.out.println("Your tax rate is 20%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross > 70000) {
int taxrate = gross * 25 / 100;
System.out.println("Your tax rate is 25%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
}
static void autocalc() {
Scanner input = new Scanner(System.in);
// Declaring the variables as an integer//
int auto;
int loan;
int interest;
int mnydwn;
int pymnt;
int year;
int month = 12;
int tap;
int term = year * month;
int spec;
System.out.println("Please enter the following information for your car loan:/n");
System.out.println("Please enter the amount of the vehicle you wish to purchase:/n");
auto = input.nextInt();
System.out.println("Please enter the amount of money you wish to put down:/n");
mnydwn = input.nextInt();
System.out.println("Please enter the interest rate:/n");
interest = input.nextInt();
System.out.println("Please enter the term of the loan (years):/n");
year = input.nextInt();
System.out.println("Processing......../n");
System.out.println("Processing............");
// Calculations//
loan = auto - mnydwn;
int intamt = loan * interest;
tap = loan + intamt;
pymnt = tap / term;
// Display//
System.out.println("Process...Complete./n");
System.out.println("Car amount:" + auto);
System.out.println("Loan recieved:" + loan);
System.out.println("Interest rate:" + interest);
// if statement for proper output of year//
if (year == 1) {
System.out.println("Your monthly payments will be" + pymnt + "for a" + year + "year" + term + "months.");
} else if (year > 1) {
System.out.println("Your monthly payments will be" + pymnt + "for" + year + "years" + term + "months.");
}
System.out.println("Total amount paid at the end of the term" + tap);
}
public static void main(String[] args) throws java.lang.Exception {
// User input//
Scanner input = new Scanner(System.in);
int count = 0; // Count for the while loop//
// Instructions on how to begin interface//
System.out.println("Hi!/n");
System.out.println("...Thanks for using D Anomaly's Finance calculator!!/n");
System.out.println("Please choose one of the following:/n");
System.out.println(" 1. Wages:/n");
System.out.println(" 2. Auto Loan:/n");
// System.out.println(" 3. Home Loan:/n");//
System.out.println("Choose 1-3");
int calc = input.nextInt();
switch (calc) {
case 1:
wagecalc();
break;
case 2:
autolcalc();
break;
case 3: // homecalc();//
break;
if (calc >= 4) {
System.out.println(" Invalid entry!!!/n");
System.out.println("Please try again:");
break;
}
}
}
}
There are a few problems here, including the following:
1.
public void wageinformation(int gross) needs to be declared static if you want to call it from main()
2.
You are calculating int gross = a * b * c right after you have received it as a parameter.
3.
You have (or had in the initial version of this post) several extra braces.
4.
The deduction and total variables are never declared within the wageinformation() method.
I would strongly suggest working through some online Java tutorials if you are looking to improve your skills.
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();