Breaking out of a loop, so as to not include a value - java

I have a question about how to break out of a loop so as not to include a value. I am supposed to enter a few integer amounts to represent grades on a test and then break out of the loop when a value of "0" is entered. However I do not want 0 to be included in the calculation of the average and the minimum. That is a little vague so here is my code.
import java.util.*;
import java.lang.*;
public class Grades
{
public static void main (String[] args)
{
Scanner myScan= new Scanner(System.in);
String input="Input numerical grade:";
System.out.println(input);
int sum=0;
int count= 0;
int max= 0;
int min= 0;
double avg=0;
boolean notNull= true;
while(notNull== true)//While grades are greater than 0 ask the question again
{
int grade= myScan.nextInt();
if(grade==0)break;
if(grade>max)
{
max=grade;
}
if(grade<min)
{
min=grade;
}
System.out.println(input);
sum +=grade;
count++;
avg= (sum)/(count);
}
System.out.println("Maximum:"+max);
System.out.println("Minimum:"+min);
System.out.println("Average:"+avg);
}
}
And here is my return when I enter a few random test scores and 0. So instead of 0 I want my minimum to be 47.
----jGRASP exec: java Grades
Input numerical grade:
89
Input numerical grade:
47
Input numerical grade:
78
Input numerical grade:
0
Maximum:89
Minimum:0
Average:71.0
----jGRASP: operation complete.

You don-t take into account that you've initialized min with zero so:
if(grade<min)
{
min=grade;
}
will never change minbecause it is already minimal non-negative integer - zero.
So take this into account with following condition:
if(min == 0 || min < grade)
{
min=grade;
}

The 0 your program is printing out isn't the 0 the user enters. It's the 0 you initialize min to. (Currently, your average is being properly calculated.)
if(grade<min)
{
min=grade;
}
min's original value is 0. So unless you're taking negative grades, grade<min will never evaluate to true.
Instead of int min = 0;, you should do this:
int min = Integer.MAX_VALUE;
Also, as I commented, because you're never touching the boolean you use as the while loop conditional check, and you're only wanting to exit the loop when the user enters 0, you can just drop the entire variable, and use while(true).

It looks like you're already breaking out of your loop before processing the 0. The reason your minimum is 0 is because you initialized it to 0, and so of course if (grade<min) { min=grade; } will never happen for any positive grade.
You have a few options:
You could set min = max = grade directly for the first grade that is input.
You could initialize min to a large number that any reasonable grade would be less than, e.g. Integer.MAX_VALUE.
You have a few possibilities for an implementation of the first option. You could store some first flag that you initialize to true then set to false. You could maintain a count of the number of grades input and initialize min/max when the count is 0 (or 1 depending on how you do it). You could initialize min/max to some special flag values that a grade could never be, e.g. -1, and set them to grade directly when they equal that flag value.
The point here is that the reason you are seeing 0 for your minimum isn't because you're processing that final 0, it's because you initialize your minimum to 0, and no grade is lower than that.

You probably want somthing like this:
import java.util.Scanner;
public class Grades {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String input = "Input numerical grade:";
System.out.println(input);
int grade = myScan.nextInt();
int sum = 0;
int count = 0;
int max = grade;
int min = grade;
double avg = grade;
while (grade != 0) {
if (grade > max) {
max = grade;
}
if (grade < min) {
min = grade;
}
count++;
sum += grade;
avg = (sum) / (count);
System.out.println(input);
grade = myScan.nextInt();
}
System.out.println("Maximum:" + max);
System.out.println("Minimum:" + min);
System.out.println("Average:" + avg);
}
}
Puts out:
Input numerical grade:
89
Input numerical grade:
47
Input numerical grade:
78
Input numerical grade:
0
Maximum:89
Minimum:47
Average:71.0

Related

A Java program with a loop that allows the user to enter a series of integers, then displays the smallest and largest numbers + the average

I've got an assignment that requires me to use a loop in a program that asks the user to enter a series of integers, then displays the smallest and largest numbers AND gives an average. I'm able to write the code that allows the user to enter however many integers they like, then displays the smallest and largest number entered. What stumps me is calculating the average based on their input. Can anyone help? I'm sorry if my code is a little janky. This is my first CS course and I'm by no means an expert.
import javax.swing.JOptionPane;
import java.io.*;
public class LargestSmallest
{
public static void main(String[] args)
{
int number, largestNumber, smallestNumber, amountOfNumbers;
double sum, average;
String inputString;
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
largestNumber = number;
smallestNumber = number;
sum = 0;
for (amountOfNumbers = 1; number != -99; amountOfNumbers++)
{
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
if (number == -99)
break;
if (number > largestNumber)
largestNumber = number;
if (number < smallestNumber)
smallestNumber = number;
sum += number;
}
average = sum / amountOfNumbers;
JOptionPane.showMessageDialog(null, "The smallest number is: " + smallestNumber + ".");
JOptionPane.showMessageDialog(null, "The largest number is: " + largestNumber + ".");
JOptionPane.showMessageDialog(null, "The average off all numbers is: " + average + ".");
}
}
The problem is that you do an extra
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
at the beginning. You don't count that in a sum. That's why you get unexpected results.
The fix would be:
replace the declarations line with:
int number = 0, largestNumber, smallestNumber, amountOfNumbers;
Remove
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
That go before the loop
Replace for (amountOfNumbers = 0 with for (amountOfNumbers = 1
This is my first CS course
Then allow me to show you a different way to do your assignment.
Don't use JOptionPane to get input from the user. Use a Scanner instead.
Rather than use a for loop, use a do-while loop.
Usually you declare variables when you need to use them so no need to declare all the variables at the start of the method. However, be aware of variable scope.
(Notes after the code.)
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int largestNumber = Integer.MIN_VALUE;
int smallestNumber = Integer.MAX_VALUE;
int number;
double sum = 0;
int amountOfNumbers = 0;
do {
System.out.print("Enter an integer, or enter -99 to stop: ");
number = stdin.nextInt();
if (number == -99) {
break;
}
if (number > largestNumber) {
largestNumber = number;
}
if (number < smallestNumber) {
smallestNumber = number;
}
sum += number;
amountOfNumbers++;
} while (number != -99);
if (amountOfNumbers > 0) {
double average = sum / amountOfNumbers;
System.out.printf("The smallest number is: %d.%n", smallestNumber);
System.out.printf("The largest number is: %d.%n", largestNumber);
System.out.printf("The average of all numbers is: %.4f.%n", average);
}
}
}
largestNumber is initialized to the smallest possible number so that it will be assigned the first entered number which must be larger than largestNumber.
Similarly, smallestNumber is initialized to the largest possible number.
If the first value entered is -99 then amountOfNumbers is zero and dividing by zero throws ArithmeticException (but maybe you haven't learned about exceptions yet). Hence, after the do-while loop, there is a check to see whether at least one number (that isn't -99) was entered.
You don't need to use printf to display the results. I'm just showing you that option.

java code, finding the min, max and average of floating point numbers

I wrote the below code everything works fine except it never executes the last loop so the last value inputted is never calculated into the min/max/average.
Any idea where I went wrong?
import java.util.Scanner;
public class Program4_JohnHuber {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
double total = 0;
//double numbers = 0;
int count = 1;
double largest = 0;
double smallest = Double.MAX_VALUE;
double average = 0;
System.out.print ("Please enter the grades, (Press enter when finished): ");
{
while (input.hasNextDouble()&& count<5)
{
double entered = input.nextDouble();
total = total + entered;
//count++;
//double average = 0;
if (count > 0)
{
average = total/count;
}
if (entered > largest)
{
largest = entered;
}
if (entered < smallest)
{
smallest = entered;
}
count++;
}
}
System.out.printf ("Your average grade is %3.2f,\n", average);
System.out.printf ("Your highest grade is %3.2f \n", largest);
System.out.printf ("Your lowest grade is %3.2f \n", smallest);
}
}
There are two errors in your program (assuming your intent is to input 5 numbers):
You're using count to indicate the number of grades you've entered already. Before you've entered any grades, how many grades have you entered? That's the value count should have, but you've initialized it to the wrong value.
The other issue is in how you've written the while:
while (input.hasNextDouble() && count<5)
Suppose you've fixed the first problem, so that it now lets you enter 5 numbers and keeps statistics on those numbers. Now it goes back up to the while loop and evaluates the boolean expression.
At this point, count is 5, so you want to exit the loop. But that doesn't happen, because input.hasNextDouble() is evaluated first. Since you're using a scanner on System.in, that means that the program waits until either you type in something that isn't blank, or until you indicate the end of input with CTRL+D on Linux or CTRL+Z on Windows. After it finds the next item in the input, it will then exit the loop if it can't find a double (e.g. you type in some letters); or if you put in a double, then it checks count.
The combination of these two errors is why the program appears to be ignoring the last input: (1) it only does the computation on 4 grades, not 5, because of the error in initializing count, and (2) it asks for a 5th grade anyway, because the parts of the while loop condition are in the wrong order.
To fix the second problem, change it to
while (count < 5 && input.hasNextDouble())
This checks count first, and exits the loop immediately when you have enough grades, instead of looking for more input.

Sentinel Value Implementation

Problem:
Write a program with a loop that lets the user enter a series of non-negative integers. The user should enter -99 to signal the end of the series. Besides -99 as sentinel value, do not accept any negative integers as input (implement input validation). After all the numbers have been entered, the program should display the largest and smallest numbers entered.
Trouble: Having trouble with implementing the loop. The sentinel value works to get out of the loop, but it still retains that value as min and max. Can anyone help me please? I'm first time user and trying to learn Java.
Code:
import java.util.Scanner;
public class UserEntryLoop
{
public static void main (String [] args)
{
/// Declaration ///
int userEntry = 0, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
/// Shortcut that shows all of these are int.
/// Integer.Min_VALUE is the lowest possible number for an int
Scanner input = new Scanner(System.in);
// Read an initial data
System.out.print(
"Enter a positive int value (the program exits if the input is -99): ");
userEntry = input.nextInt();
// Keep reading data until the input is -99
while (userEntry != -99) {
// Read the next data
System.out.print(
"Enter a positive int value (the program exits if the input is -99): ");
userEntry= input.nextInt();
}
if (userEntry > max) //// if the max was < X it would print the initialized value.
max = userEntry; /// To fix this the max should be Integer.MAX_VALUE or MIN_VALUE for min
if (userEntry < min)
min = userEntry;
System.out.println("The max is : " + max);
System.out.println("The min is : " + min);
}
}
You should test in your loop (and I'd use Math.min and Math.max respectively, instead of a chain of ifs). Also, don't forget to check that the value isn't negative. Something like,
while (userEntry != -99) {
// Read the next data
System.out.print("Enter a positive int value (the program exits "
+ "if the input is -99): ");
userEntry= input.nextInt();
if (userEntry >= 0) {
min = Math.min(min, userEntry);
max = Math.max(max, userEntry);
}
}
Let's simplify the problem with an array and a single loop.
int[] test = { 1, 2 };
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int userEntry : test) {
min = Math.min(min, userEntry);
max = Math.max(max, userEntry);
}
System.out.println("The max is : " + max);
System.out.println("The min is : " + min);
and I get
The max is : 2
The min is : 1

Java error in calculation when comparing largest and smallest numbers & sum with while loop

Here is my assignment:
Write a program to read a list of nonnegative integers and to display the largest integer, the smallest integer, and the average of all the integers. The user
indicates the end of the input by entering a negative sentinel value that is not
used in finding the largest, smallest, and average values. The average should
be a value of type double so it will be computed with a fractional part.
I've gotten different parts to work with different methods: Method A makes the maximum and minimum correct and the sum wrong and Method B makes the sum and maximum correct and the minimum wrong. The following code demonstrates Method B. Some variables are commented out:
public class testthis2
{
public static void main(String[] args) {
System.out.println("Enter Numbers of Nonnegative Integers.");
System.out.println("When complete, enter -1 to end input values.");
Scanner keyboard = new Scanner(System.in);
//int max = keyboard.nextInt();
int max = 0;
int min = max; //The max and min so far are the first score.
//int next = keyboard.nextInt();
int count = 0;
int sum = 0;
boolean areMore = true;
boolean run_it = false; //run it if its true
//if (max <= -1) {
// System.out.println("Thanks for playing!");
// run_it = false;
//}
// else
// run_it = true;
while(areMore) //always true
{
int next = keyboard.nextInt();
//int max = 0;
// min = max;
if (next < 0) { //if -1 is entered end loop.
areMore = false;
run_it = false;
break;
}
else //run this badboy
if(next >= max)
max = next;
else if(next <= min)
min = next;
run_it = true;
sum += next;
count++;
}
if (run_it = true)
System.out.println("The highest score is " + max);
System.out.println("The lowest score is " + min);
System.out.println("count " + count);
System.out.println("sum " + sum);
System.out.println("average " + (double)(sum/count));
System.out.println("Thanks for playing!");
}
}
When I run this test, the maximum, sum, count, and average are all correct. However, the minimum is wrong, because 0 was clearly not entered. Here's an example test-run:
When complete, enter -1 to end input values.
37
25
30
20
11
14
-1
The highest score is 37
The lowest score is 0
count 6
sum 137
average 22.0
Thanks for playing!
Any help would be greatly appreciated. Thanks!
The smallest iteger is always 0 because there is no nonnegative integer that is less then 0 :)
if(next <= min) // for nonnegative integer this expression will return true only for 0
min = next;
So try to initialize the "min" variable as Integer.MAX_VALUE. I believe it will help you.
There are 2 problems with the code:
You initialize min to 0 so it never gets updated because it will always be <= any valid number you enter. Try initializing it to Integer.MAX_VALUE. conversely also initialize max to Integer.MIN_VALUE
You are not correctly computing the average value: (double)(sum/count) will first do integer division which truncates the value THEN gets cast to double do this instead ((double)(sum )/count) or optionally make the type of sum a double.
Looks like you initialize min and max both to 0.
Then the only code that will ever change min or max is based on user input. If the input value (next) is >= max, max will change to that value. This should happen on the first input.
The problem is you try setting min the same way. if (next <= min), but min was initialized to 0, so next can only be <= min if next is less than 0.
You need to initialize max and min on the user's first input. They should both start equal to the user's first input before you compare future inputs to their value.

Golf score program?

So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.
You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;
You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
Don't always divide by 10 - use the value of counter.
Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;
You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.
while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.

Categories

Resources