Hey I'm trying to work out the minimum and maximum value from user input while disregarding the loop terminated value, which is -1. I understand how to do everything except how to disregard -1 when calculating minimum value for the input.
Here's the code I've got so far:
int value = 0;
int max = value;
int min = max;
Scanner scan = new Scanner(System.in);
while (value != -1) {
System.out.print("Value: ");
value = scan.nextInt();
if (min > value) {
min = value; }
if (max < value) {
max = value; }
}
System.out.println("Min = " + min);
System.out.println("Min = " + min);
How can I calculate the minimum value while disregarding -1?
Thanks.
You turn the loop into a never-ending loop, and add a break when termination number is detected:
Scanner scan = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (;;) { // never-ending loop
System.out.print("Value: ");
if (! scan.hasNextInt()) {
System.out.println("** Invalid input **");
scan.nextLine(); // discard invalid input
continue; // loop back to prompt again
}
int value = scan.nextInt();
if (value == -1) // termination number
break;
if (value < min)
min = value;
else if (value > max)
max = value;
}
System.out.println("Min = " + min);
System.out.println("Max = " + max);
Also fixed:
Initialization of min and max (otherwise min will likely always be 0)
Validation of Scanner input (so program doesn't die with exception on bad input)
Printing of max (was printing min twice)
Indentation (so code structure is clearly visible to human readers)
Add if (value == -1) break; right before the line that starts withif (min > value). This causes the loop to break once the terminal (-1) character is read.
For clarity, you can then change your loop condition to while(true). This is a pretty common idiom for this situation.
Related
My programs asks the user to input integers (on a loop) until they input -99; which will then display the highest and lowest numbers of the input integers. I have a variable called count, that increments every time the user puts in a new integer, to keep track of the number of integers inputted by the user. How can I have -99 not included as one of the integers and not incrementing count?
Code:
//variables
int num = 0, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
low = num;
high = num;
//loop
while(num != -99){
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++;
if (num == -99 && count == 0)
{
count--;
System.out.println("You did not enter a number");
} //outer if end
else {
//higher or lower
if(count > 0 && num > high)
{
high = num;
} //inner else end
else if(count > 0 && num < low)
{
low = num;
} //inner else if end
else
{
} //inner else end
} //outer else end
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
You approach is good, but you missed some points,
your condition to find max or min is also wrong because you have to write them separately.
User Entered any value or not, you have to decide this outside the loop.
You have to initialize high and low with first input.
I am trying to make some correction in your program, just changing the required part. Hope it will help you.
//variables
int num = 0, count = 0, high =0 , low = 0;
Scanner userInput = new Scanner(System.in);
//loop
while(true){
//Using infinite loop, we will break this as per condition.
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
if(num == -99)
{
break;
}
count++;
if(count == 1)
{//initialize high and low by first number then update
high = num;
low = num;
}
//to check highest
if(num > high)
{
high = num;
}
//to check smallest
if(num < low)
{
low = num;
}
}
if (count == 0)
{//Here we check that if user enter any number or directly entered -99
System.out.println("You did not enter a number");
}
else
{
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
}
I would recommended the following solution :
First of all, get a number from the user before the loop.
Then check if the number is -99 or not.
You know what to do if it is.
If not, start a do-while loop and do the following :
Increment the count.
Update your low and high.
And the last statement of the loop body will get another number from the user.
The while condition after the loop body will check that the latest number entered is not -99.
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
Please help me to figure out my mistakes. When I input scores in ascending order like 4,5 the minimum is given as 100.I don't know how to change it then?
Here is my code :
float score=0,min=100,max=0,sum1=0,count=0,sum2=0;
float average,sd;
Scanner a=new Scanner(System.in);
while(score>=0)
{
System.out.println("enter the score(a negative score to quit)");
score=a.nextInt();
if(score<0)
break;
if(score>=max){
max=score;
sum1+=max;
}
else
{
min=score;
sum2+=min;
}
count++;
}
average=(sum1+sum2)/(count++ );
System.out.println("the average : " + average);
System.out.println( "the maximum score: "+ max);
System.out.println("the min score: "+ min );
I think you're overcomplicating the problem: you should try thinking about the task at hand in logical steps:
Have users input numbers
Add the next int that came in to the total score
Check if the next int is > last known maximum, if so, set the last known maximum to next int's value
Else check if the next int < last known minimum, if so, set the last known minimum to next int's value
Continue while there is more input available
Print the maximum score
Calculate and print the average score (totalScore / amountOfInputs)
Print the minimum score
That'd look like this:
import java.util.*;
public class MaxMinAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double score, currentMinimum = Integer.MAX_VALUE, currentMaximum = Integer.MIN_VALUE, count;
while (in.hasNextInt()) {
int nextInt = in.nextInt();
if (nextInt < 0) { //break out of the loop
break;
} else {
score += nextInt;
count++;
if (nextInt > currentMaximum) {
currentMaximum = nextInt;
} else if (nextInt < currentMinimum) {
currentMinimum = nextInt;
}
}
}
System.out.println("Max: " + currentMaximum);
System.out.println("Avg: " + (score / count));
System.out.println("Min: " + currentMinimum);
}
}
change your else to else if (score < min) and you are getting the correct minimum.
The reason why, it checks if score if greater then the current max, if this is not the case then it simply does assume, due to the else, that score is the new min.
if (score >= max) {
max = score;
}
else if (score < min){
min = score;
}
// Just add the score value to the sum, it doesn´t matter if it´s min or max
sum2 += score;
count++;
Simplify:
while((score = a.nextInt()) >= 0) {
min = Math.min(min, score);
max = Math.max(max, score);
sum += score;
average = sum / count++;
}
when I execute this program, it prints the max value just fine, however the min value always prints to zero. I continue to scratching my head... Can anyone see what is wrong here? Thanks for looking.
import java.util.Scanner;
public class MinMax
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int [] numbers = new int[5];
int max = numbers[0];
int min = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Enter your next number:");
numbers[i] = kb.nextInt();
if (numbers[i] > max)
{
max = numbers[i];
}
if (min > numbers[i])
{
min = numbers[i];
}
}
System.out.println("The maximum value in your array is " + max);
System.out.println("The minimum value in your array is " + min);
}
}
The issue is that when the array is declared, the ints in the array are set to 0. Setting the min to numbers[0] would set min to 0. If that's not your min, your code will fail.
In this case, you don't need the array - you could just store whatever the user inputted. That aside, just check whether i==0 and when it does, set min and max to numbers[0]. (If you didn't do the same for max, an array of all negatives would fail.)
It's simple. The min variable is never updated because every time that min > numbers[i] is evaluated returns false. Let's to see an example:
min = 0.0 > numbers[i] = 4.5 -> false
min = 0.0 > numbers[i] = 3.8 -> false
min = 0.0 > numbers[i] = -8.9 -> true, min = -8.9
min = -8.9 > numbers[i] = 7.5 -> false
min = -8.9 < numbers[i] = 5.6 -> false
The value of min is: -8.9
With Java 8 you can get the max and min values easy with lambdas:
max = Arrays.stream(numbers).max().getAsDouble();
min = Arrays.stream(numbers).min().getAsDouble();
As other answers here are saying, the problem is that numbers[0] starts out initialized to 0, so regardless of the numbers the user enters, your code still finds 0 to be the minimum value.
What you need is an extra state to represent "I don't have any minimum value yet". You could use an extra boolean variable to represent this tate, or if you can use the Integer wrapper type, you can use null.
For example:
Integer minimum = null;
Integer maximum = null;
for (int i = 0; i < 5; i++) {
int number = kb.nextInt();
if (minimum == null || number < minimum) {
minimum = number;
}
if (maximum == null || number > maximum) {
maximum = number;
}
}
System.out.println("minimum: " + minimum);
System.out.println("maximum: " + maximum);
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.