Reputation: 51
hi I am writing this array in order to read in 30 integers and read out the min and max. I have solved the max but the minimum is not working, all help is appreciated, As stated i have solved the max , but the minimum is not working
import java.io.*;
import java.util.*;
public class Uppgift1
{
public static void main(String args[])throws IOException
{
BufferedReader stdin = new BufferedReader
(new InputStreamReader (System.in));
int antal = 0;
int summa = 0;
double medel = 0;
int min;
int max = 0;
System.out.print("Hur manga tal vill du mata in(max 30)? ");
antal = Integer.parseInt(stdin.readLine());
int [] array = new int[antal];
for(int i = 0; i<antal; i++){
array[i] = Integer.parseInt(stdin.readLine());
summa = summa +array[i];
medel = summa / antal;
}
System.out.println("summan av talen är "+summa);
System.out.println("medel av alla tal är "+medel);
for (int i = 0; i < antal; i++)
{
while(array[i]>max)
{
max=array[i];
}
}
System.out.println("max numret är " + max);
for (int i = 0; i < antal; i++)
{
while(array[i]<min)
{
min=array[i];
}
}
System.out.println("min numret är " + min);
}}
Upvotes: 0
Views: 205
Reputation: 106389
Initialize your min
variable with the largest possible integer (Integer.MAX_VALUE
). Any number that's smaller than this will be found.
Initialize your max
variable with the smallest possible integer (Integer.MIN_VALUE
). Any number that's larger than this will be found.
Upvotes: 0
Reputation: 726479
The min
starts off at zero, so it compares lower than any positive number the user enters.
In general, you start off the minimum high and your maximum low before entering a loop. This sacrifices two numbers from the available range, which is usually OK. Alternatively, you could set both min
and max
to the initial element of the sequence.
The other problem is your use of while
instead of if
: it's not hurting the result, but it does hurt readability a lot.
Finally, you can search for both the min
and the max
in the same loop.
Upvotes: 5
Reputation: 1132
do this for calculating min and max suppose you have array called numbers. initialise variables min,max as given below
int min = numbers[0];
int max = numbers[0];
for(int i=1; i< numbers.length(); i++) {
if(min>numbers[i]) {
min = numbers[i];
}
if(max<numbers[i]) {
max = numbers[i];
}
}
System.out.println("Max Is : " + max);
System.out.println("Min Is : " + min);
Upvotes: 1
Reputation: 5145
max= 0;
min=0;
for (int i = 0; i < antal; i++) {
max = Math.max(max, array[i]);
min = Math.min (min, array[i]);
}
Upvotes: 0