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!");
}
Related
The idea of my code is that it asks user the income of each month, until the user imputs negative value, which should not be added to the total income and which should be shown in output, but ignored in calculations.
Then the code calculates the total income (ignoring the last negative value), the average income (ignoring the negative value) and the biggest/maximum value of all values. I don't have problems getting right that maximum value. But how could I ignore the negative income in calculations, and maby even not to add it at all to the array?
The problem is that the calculation adds also the negative value/income to the total sum and average income calculations. And it does not ignore the month of the negative income.
Here is my code so far:
package income;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Income {
public static void main(String[] args) {
int sum = 0;
int months = 0;
Scanner input = new Scanner(System.in);
System.out.println("Write the income of each month.");
ArrayList<Integer> array = new ArrayList<Integer>();
System.out.println("Write the income of month 1: ");
int income = input.nextInt();
sum += income;
months++;
array.add(income);
while(true){
months++;
System.out.println("Write " + months + ". month income: ");
if(income >= 0){
income = input.nextInt();
sum += income;
array.add(income);
}
else if (income < 0){
break;
}
}
/*This did not work
for(int i= 0; i < array.size(); i++){
if(income < 0){
array.remove(i);
}
}*/
months--;
System.out.println("The total income is " + sum);
System.out.println("The average income is " + sum/months);
//This one below works fine
System.out.println("The biggest income is " + Collections.max(array));
}
}
Although you are indeed adding the last negative number into account in the calculations, this is not the ultimate reason why your code is not working. You are actually checking whether the previous input you read is greater than 0 here:
while(true){
months++;
System.out.println("Write " + months + ". month income: ");
if(income >= 0){ <------
income = input.nextInt();
So the loop will only stop if the previous input is less than 0. In other words, when you enter e.g. -1 in, the input is not checked until the next iteration of the loop, at which point -1 has already been added to the array. Therefore, you should instead check income >= 0 immediately after nextInt:
System.out.println("Write the income of each month.");
ArrayList<Integer> array = new ArrayList<>();
while(true){
months++;
System.out.println("Write the income for month" + months + ":");
int income = input.nextInt();
if(income >= 0){
sum += income;
array.add(income);
}
else {
break;
}
}
Note that I've also removed the bit between Write the income of each month. and the while loop, as it is redundant.
I suppose this is what you are looking for.
var list = new ArrayList<Integer>();
var in = new Scanner(System.in);
var i = 0;
System.out.println("Write Income of Each Month.");
while (true)
{
System.out.print("Write " + ++i + ".month income : " );
int num = in.nextInt();
if (num < 0)
{
int sum = list.stream().mapToInt(Integer::intValue).sum();
double avg = (double) sum / --i;
int max = Collections.max(list);
System.out.printf("Sum : %d\nAverage : %f\nBiggest Number : %d\nNegative No. %d", sum ,avg, max, num);
break;
}
else
{
list.add(num);
}
}
You could use the Integer.signum(int) function to know whether the value is negative (returned value = -1) or zero (returned value = 0) or positive (returned value = 1). So, basically ignore if Integer.signum(income) == -1
The exercise asked me to calculate the average, maximum, and minimum. My code fulfills that purpose, however I need to include somewhere in my code that the exam grades entered by the user MUST be between 0 and 100. What is the best way to include this?
Here is my code.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class hw
{
public static void main ( String[] args )
{
int maxGrade = Integer.MIN_VALUE;
int minGrade = Integer.MAX_VALUE;
int count=0;
int total=0;
final int SENTINEL = -1;
int score;
Scanner scan = new Scanner( System.in);
System.out.println( "To calculate the class average, enter each test
score.");
System.out.println( "When you are finished, enter a -1.");
System.out.print( "Enter the first test score > ");
score = scan.nextInt();
while (score != SENTINEL )
{
total += score;
count ++;
if( score > maxGrade)
maxGrade = score;
if( score < minGrade)
minGrade = score;
System.out.print("Enter the next test score > ");
score = scan.nextInt();
}
if (count != 0)
{
DecimalFormat oneDecimalPlace = new DecimalFormat("0.0");
System.out.println( "\nThe class average is "
+ oneDecimalPlace.format( (double) (total) / count ));
System.out.println( "The minimum value is " + minGrade);
System.out.println( "The maximum value is " + maxGrade);
}
else
System.out.println("\nNo grades were entered");
}
}
Thank you!
Create a nested loop that will stop executing once the user has met the criteria. Something like this:
while (score < 0 || score > 100)
{
System.out.println("please enter a number between 0 and 100.");
while(!scan.hasNextInt())
{
scan.next();
}
score = scan.nextInt();
}
Note that this code has not been tested, this is just an idea of what it should look like.
//Setting my variables.
Scanner keyboard = new Scanner(System.in); // Initalizing keyboard to scanner input
int quarter;
double balance, intrestRate;
boolean correct = false;
//Loop iterations to resolve error, and determine value for each input.
do{ //Beginning loop for number of quarters, must be between 1-10
System.out.println("Enter a number between 1 and 10 for the amount of quarters");
quarter = keyboard.nextInt();
if(quarter >= 1 && quarter <= 10) //If quarter is between 1 and 10
{
System.out.println("You have " + quarter + " quarters.");
correct = true;
}
else
{
System.out.println("Number of quarters must be between 1 and 10");
correct = false;
}
}while(!correct);
do{ //Second loop for rate of intrest.
System.out.println("Enter intrest rate without percent a sign. Must be greaters than 5% and less than 25%.");
intrestRate = keyboard.nextDouble();
if (intrestRate >= 5 && intrestRate <=25)
{
System.out.println("You have selected a " + intrestRate + "% rate of intrest.");
correct = true;
}
else
{
correct = false;
}
}while(!correct);
}
}
So, this is my code. I'm experimenting with loops, and if-else type statements. I feel like, MY approach is way to complicated and could be easily summarized or revised period. Does anyone know how to approach with, with only declaring one do statement? This code is just in the beginning phases of my experiment and has much work to do. But before I move on, I was hoping for another set of eyes!
Use of infinite loop with break on valid input. Enhanced to handle bad input.
Scanner keyboard = new Scanner(System.in);
int quarter;
while (true) {
System.out.print("Enter number of quarters (1-10): ");
if (keyboard.hasNextInt() && (quarter = keyboard.nextInt()) >= 1 && quarter <= 10)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Number of quarters must be between 1 and 10");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have " + quarter + " quarters.");
double intrestRate;
while (true) {
System.out.print("Enter interest rate (5%-25%), without percent sign: ");
if (keyboard.hasNextDouble() && (intrestRate = keyboard.nextDouble()) >= 5 && intrestRate <= 25)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Interest rate must be between 5% and 25%");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have selected a " + intrestRate + "% rate of interest.");
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();
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--;
}