-2

I am trying to gather input from the user, and then denote which one of their numbers is the highest, and which one is the lowest.

int highest = Integer.MAX_VALUE, lowest=Integer.MIN_VALUE, number=0;
Scanner input = new Scanner(System.in);
    for (int j=0; j<5; j++) {
       System.out.print("Enter five integers: ");
       number = input.nextInt();
    }
    if (number > highest){    
       highest = number;
    }
    if (number < lowest){
       lowest = number;
    }
    System.out.println("Your highest number is: " + highest);
    System.out.println("Your lowest number is: " + lowest);

It is giving me the maximum and minimum that an Integer can be ( 214... and -214...).

Rajan Kali
  • 12,627
  • 3
  • 25
  • 37

2 Answers2

1

You should swap the highest and lowest value, a number cannot possibly be greater than highest value, highest should start with MIN and lowest should start with MAX and move the comparison inside for loop

int highest = Integer.MIN_VALUE, lowest = Integer.MAX_VALUE, number = 0;
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
  • Hey, that worked! Thank you! I kept thinking to switch around things but didn't realize that the min/max is what needed to be switched. – NayxAshanti May 13 '23 at 23:58
1

First, make certain the prompt for five integers is before the loop and the input and use of the entered values are inside the loop.

Here are some alternatives.

  1. You can also use IntSummaryStatistics. It's used quite often in stream applications but it can also be used in imperative programming.
IntSummaryStatistics stats = new IntSummaryStatistics();
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
    stats.accept(input.nextInt());
}
System.out.println("Minimum = " + stats.getMin());
System.out.println("Maximum = " + stats.getMax());
  1. Or you can use Math.min() and Math.max()
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for (int i = 0; i < 5; i++) {
     int val = input.nextInt();
     max = Math.max(max, val);
     min = Math.min(min, val);
}
System.out.println("Minimum = " + min);
System.out.println("Maximum = " + max);
WJS
  • 36,363
  • 4
  • 24
  • 39