3.4k views
1 vote
60 POINTS

IN JAVA

In this exercise, you will need to write a program that asks the user to enter different positive numbers.

After each number is entered, print out which number is the maximum and which number is the minimum of the numbers they have entered so far.

Stop asking for numbers when the user enters -1.

Possible output:

Enter a number (-1 to quit):
100
Smallest # so far: 100
Largest # so far: 100
Enter a number (-1 to quit):
4
Smallest # so far: 4
Largest # so far: 100
Enter a number (-1 to quit):
25
Smallest # so far: 4
Largest # so far: 100
Enter a number (-1 to quit):
1
Smallest # so far: 1
Largest # so far: 100
Enter a number (-1 to quit):
200
Smallest # so far: 1
Largest # so far: 200
Enter a number (-1 to quit):
-1

1 Answer

5 votes

import java.util.Scanner;

public class JavaApplication75 {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int num = -2, largest = -1, smallest = -1;

while (true){

System.out.println("Enter a number (-1 to quit):");

num = scan.nextInt();

while (num < 0){

if (num == -1){

System.exit(0);

}

num = scan.nextInt();

}

if (num > largest){

largest = num;

}

if (num < smallest || smallest == -1){

smallest = num;

}

System.out.println("Smallest # so far: "+smallest);

System.out.println("Largest # so far: "+largest);

}

}

}

I hope this helps!

User Marcone
by
5.0k points