Using do-while loop, Write a program that will ask for five (5) integer numbers. Determine the highest and lowest value. Consider the sample output.
Output:
Enter 1st number: 5
Enter 2nd number: 10
Enter 3rd number: 2
Enter 4th number: 50
Enter 5th number: 30
The highest value is: 50
The lowest value is: 2
I honestly don't know how to answer this since my professor haven't discussed about determining the numbers using a do while loop. So far, here's what I have
Edit: I ended up with this code but I don't know how to make the 1st 2nd 3rd 4th 5th show up.
enter code here
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp=new Scanner(System.in);
int a = 1;
int i =1;
int highestNumber=0;
int lowestNumber=0;
while (i < 5) {
System.out.println("Enter " a " number ");
int numbers = inp.nextInt();
if(highestNumber==0) {
highestNumber = numbers;
}else if(numbers>highestNumber) {
highestNumber=numbers;
};
if(lowestNumber==0) {
lowestNumber = numbers;
}else if(numbers<lowestNumber) {
lowestNumber=numbers;
};
System.out.println("The Highest Number is: " highestNumber);
System.out.println("The Lowest Number is: " lowestNumber);
}
}
CodePudding user response:
Some homework improvements to meet the requirements:
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] nums = new String[] {"1st", "2nd", "3rd", "4th", "5th"};
try(Scanner inp = new Scanner(System.in)) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int i = 0;
do{
System.out.print("Enter " nums[i] " number: ");
int num = inp.nextInt();
if(num < min) min = num;
if(num > max) max = num;
} while( i < nums.length);
System.out.println("\nThe highest value is: " max);
System.out.println("The lowest value is: " min);
} catch(InputMismatchException e) {
e.printStackTrace();
}
}
}
CodePudding user response:
Please do some research before asking a question like this. While-Loops are well documented all over the internet. That said, this should probably work (haven't tested it though):
public static void main(String[] args) {
Scanner inp=new Scanner(System.in);
int[] numbers = new int[5];
int i = 0;
while (i < numbers.length) {
System.out.println("Enter number " i);
numbers[i] = inp.nextInt();
i ;
}
}