Beginner: Min Value in Array (Java) - java

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);

Related

Finding Max/Min values in user-defined integer array. Negative numbers included

All of this works to some degree. Here's the issue:
1: User specifies array size. Let's assume size = 5.
2: User inputs 1 2 3 4 5
3: MAX number and MIN number works. All good.
ISSUE:
2: User inputs 5 4 3 2 1
3: MAX number fails. It's defaulted to Integer.MAX_VALUE
This is defined above:
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
The Code is here:
for (int i = 0; i < numbers.length; i++) { //READ INPUT, find smallest / largest
numbers[i] = myScanner.nextInt();
sum += numbers[i]; //ADD Array element values to sum.
if (numbers[i] < min) { //Loop through array to find smallest value
min = numbers[i];
} else if (numbers[i] > max) { //Loop through array to find largest value
max = numbers[i];
}
}
Note: This is a code snippet. "sum" belongs to the rest of the code.
Remove the "else", the two conditions can be true.
for (int i = 0; i < numbers.length; i++) {largest
numbers[i] = myScanner.nextInt();
sum += numbers[i];
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] > max) {
max = numbers[i];
}
}
If you dry-run the code
User inputs 5 4 3 2 1
5<min(Integer.MIN_VALUE) so min = 5
4<min(5) so min = 4
3<min(4) so min = 3
2<min(3) so min = 2
1<min(2) so min = 1
Since you are having an else-if condition.
It never goes to the else condition and max is always Integer.MIN_VALUE
So remove the else-if to if condition.
just remove else in your code, because two condition can be true at the same time

how to get the sum, average, minimum and maximum of five numbers-java using do-while loop

I'm trying to get the sum, average, minimum and maximum of five numbers but somehow I get this output. I'm trying to re-code it all over again but it is still the same. Can you help me check this guys...
Here's my code:
import java.util.*;
public class Kleine {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double average;
int count = 0, sum = 0, num, min = 0, max = 0;
System.out.println("Please enter the number of numbers you wish to evaluate:");
do {
num = scan.nextInt();
sum += num;
count++;
} while (count < 5);
average = sum / 5;
{
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
System.out.println("Your average is: " + average);
System.out.println("The sum is: " + sum);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
Here's the output:
Please enter the number of numbers you wish to evaluate:
1
10
5
-3
6
Your average is3.0
The sum is:19
Your maximum number is 6
Your minimum number is 0
BUILD SUCCESSFUL (total time: 19 seconds)
The minimum and maximum numbers goes somewhere...
a little advice please...
The best way to handle the min/max values is to keep track of them as your read in each value:
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i=0; i < 5; ++i) {
num = scan.nextInt();
if (num > max) max = num;
if (num < min) min = num;
sum += num;
}
double average = sum / 5.0d;
I seed the max and min values with the smallest/largest integer values, respectively. This lets us capture the actual min and max values as they are read in. Also, I think that a basic for loop works better here than a do while loop.
Note that I compute the average using a double type, because it may not be a pure integer value (even in your sample data the average is not an integer).
Use
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
And your
{
if(num>max)
max=num;
if(num<min)
min=num;
}
needs to be inside the do-while loop, or else it runs only for the last value of number entered.
For a start you can use Math.min & Math.max. The average is sum / count.
An example getting a min number without a loop would be:
long min = Integer.MAX_VALUE;
min = Math.min(min, 9);
min = Math.min(min, 4);
min = Math.min(min, 6);
// min = 4
Do something similar for max.
You'd also be better off starting with a list or array of numbers. Get the output right, then add more complicated things like user input.
You can do it this way without defining number of integers to read:
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Next number?");
numbers.add(in.nextInt());
IntSummaryStatistics summaryStatistics = numbers.stream()
.mapToInt(Integer::valueOf)
.summaryStatistics();
System.out.println(String.format("Max: %d, Min: %d, Average: %s, Sum: %d", summaryStatistics.getMax(), summaryStatistics.getMin(), summaryStatistics.getAverage(), summaryStatistics.getSum()));
}
}
}
If I just change the existing code, the logic should be like below:
do{
num=scan.nextInt();
sum+=num;
if(count==0){
min=num;
max=num;}
if(num>max)
max=num;
if(num<min)
min=num;
count++;
}while(count<5);
average = sum/5;
The issue was that your min-max condition was outside the loop and you were initializing min and max by 0. You should set min/max to your first input number.
Min and Max were now equal to the max and min of integer. now if any number is less than min and greater than max, min and max takes their position. The average and the sum functionality was great. The problem in your code was that it was getting the max and min after the loop for input has executed. The flow was wrong.
import java.util.*;
public class Kleine {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
double average;
int count=0, sum=0, num=0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("Please enter the number of numbers you wish to evaluate:");
do{
if(num>max) max=num;
if(num<min) min=num;
num=scan.nextInt();
sum+=num;
count++;
}while(count<5);
average = sum/5;
System.out.println("Your average is"+average);
System.out.println("The sum is:"+sum);
System.out.printf("Your maximum number is %d\n",max);
System.out.printf("Your minimum number is %d\n",min);
}
}

How to pull the maximum and minimum values from an array?

I am using arrays for a programming project due tonight. I am able to add up all the numbers of the array, but from there I am unable to remove the maximum and minimum values from it. My attempt and the actual project description is below...
In the sport of diving, seven judges award a score between 0 and 10, where each score may be a floating-point value. The highest and lowest scores are thrown out and the remaining scores are added together. The sum is then multiplied by the degree of difficulty for that dive. The degree of difficulty ranges from 1.2 to 3.8 points. The total is then multiplied by 0.6 to determine the diver’s score.
Write a computer program that inputs a degree of difficulty and seven judges’ scores and outputs the overall score for that dive. The program should ensure that all inputs are within the allowable data ranges.
package baker;
import java.util.Scanner;
public class DiveScoreDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double total = 0;
double totalFinal = 0;
double divingScores[] = new double[7];
double input;
double difficultyInput = 0;
double minimum = divingScores[0];
double maximum = divingScores[0];
for (int i = 1; i < divingScores.length + 1; i++)
{
System.out.println("Judge " + i + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
}
}
while (difficultyInput < 1.2 || difficultyInput > 3.8)
{
System.out.println("Difficulty Rating: ");
difficultyInput = keyboard.nextDouble();
}
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
System.out.printf("\nThe overall score for the dive: %.1f\n", total);
}
}
The portion in particular that I am struggling with is here:
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
The code runs and produces a correct output, but it does not seem to subtract the max and min values and the problem requests... Thanks for the help!
You have forgotten to add each judge's score to the array divingScores. You can fix this by changing the first for loop to the following:
for (int i = 0; i < divingScores.length; i++)
{
System.out.println("Judge " + (i + 1) + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
divingScores[i] = input;
}
}
You should also initialize minimum as:
minimum = 0
If you do not, every score above 0 will not be considered for the minimum.
You never set the array values in the else branch within your for loop, it should look like this:
if(input < 0 || input > 10) {
System.out.println("Invalid Score");
return;
} else {
divingScores[i] = input;
total += input;
}
Before the second loop, you can use Java 8 functional programming to get the minimum and maximum like this, which is shorter:
double minimum = Arrays.stream(divingScores).min().getAsDouble();
double maximum = Arrays.stream(divingScores).max().getAsDouble();
Alternatively, you should initialize the minimum and maximum values properly, one way to do this in general for at least one element in the array is:
double minimum = Double.MAX_VALUE; // Use your maximum in your case
double maximum = Double.MIN_VALUE; // Use your minimum in your case
You can sort the array and then add the array elements except first and last element of sorted array which will automatically remove the minimum and maximum
Arrays.sort(divingScores);
double ans=0;
for(int i=1;i<divingScores.length-1;i++){
System.out.println(divingScores[i]);
ans+=divingScores[i];
}

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.

Categories

Resources