Using a while loop to enter multiple ints by the user and find max and min

so my question about homework is asking the user for integers and find the max and min of these integers. Use a loop and -99 for break loop.Below is my code, but my question is, is there a shorter way for this? feel free to comment and I appreciate your time reading this.

  Scanner input=new Scanner(System.in);
  int num1,num2,max,min;
  System.out.print("enter a number: ");
  num1=input.nextInt();
  System.out.print("enter another number: ");
  num2=input.nextInt();
  max=Math.max(num1,num2);
  min=Math.min(num1,num2);


  while (num2!=-99){
      System.out.print("enter a number or -99 to stop: ");
      num2=input.nextInt();
      if(num2!=-99){
      max=Math.max(max,num2);
      min=Math.min(min,num2);
      }

  }
  System.out.println("largest is: "+max);
  System.out.println("Smallest is: "+min);
+4
source share
3 answers

So, after working on this. Finally I did it. This one has a small mistake, but I really don't want to fix it, so if I still want to edit it, then I will be my guest.

 Scanner input = new Scanner(System.in);
    int studentNum = 0;
    ArrayList<Integer> calc = new ArrayList<Integer>();

    while (studentNum <= 100) {

        System.out.print("Enter a number: ");
        calc.add(input.nextInt());

        studentNum += 1;

        if (input.nextInt() == -99) {
            break;
        }

    }

    int min = Collections.min(calc);
    int max = Collections.max(calc);

    for (int i = 0; i < calc.size(); i++) {
        int number = calc.get(i);
        if (number < min)
            min = number;
        if (number > max)
            max = number;
    }

    System.out.println("Max is " + max);
    System.out.println("Min is " + min);

It does exactly what you want. However, there was a problem checking the output signal.

 if (input.nextInt() == -99) {
            break;
        }

, userInput -99, min max. , , , userInput , -99. , .

, .

EDIT , .

0

num2 != -99, ,

, min max, . , , num2 != -99 while

+2

. , , , :

  • ( ), -99 ?
  • 2 ? , ? min max.
  • , (num2!=-99) ?

Pro:

  • , ? ?
  • , - (, )?
  • , enter - ?

:

0
source

Source: https://habr.com/ru/post/1685640/


All Articles