Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the max and min values from a set of numbers entered?

Tags:

java

max

min

Below is what I have so far:

I don't know how to exclude 0 as a min number though. The assignment asks for 0 to be the exit number so I need to have the lowest number other than 0 appear in the min string. Any ideas?

int min, max;

Scanner s = new Scanner(System.in);
System.out.print("Enter a Value: ");
int val = s.nextInt();
min = max = val;

while (val != 0) {
  System.out.print("Enter a Value: ");
  val = s.nextInt();
  if (val < min) {
      min = val;
  }
  if (val > max) {
     max = val;
  }
};
System.out.println("Min: " + min);
System.out.println("Max: " + max);
like image 524
user2934299 Avatar asked Dec 20 '22 22:12

user2934299


2 Answers

Here's a possible solution:

public class NumInput {
  public static void main(String [] args) {
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;

    Scanner s = new Scanner(System.in);
    while (true) {
      System.out.print("Enter a Value: ");
      int val = s.nextInt();

      if (val == 0) {
          break;
      }
      if (val < min) {
          min = val;
      }
      if (val > max) {
         max = val;
      }
    }

    System.out.println("min: " + min);
    System.out.println("max: " + max);
  }
}

(not sure about using int or double thought)

like image 179
Maxime Chéramy Avatar answered Dec 22 '22 10:12

Maxime Chéramy


You just need to keep track of a max value like this:

int maxValue = 0;

Then as you iterate through the numbers, keep setting the maxValue to the next value if it is greater than the maxValue:

if (value > maxValue) {
    maxValue = value;
}

Repeat in the opposite direction for minValue.

like image 20
MattSenter Avatar answered Dec 22 '22 11:12

MattSenter