We've already tried comparing 3 numbers to see the largest among all, so let's try a more complicated mission where we locate the position of the largest among 5 numbers. There are only 4 possible cases for this mission:
- if the largest digit is the first digit, print "Leftmost"
- if the largest digit is the third digit, print "Middle"
- if the largest digit is the last digit, print "Rightmost"
- if none of the above is correct, print "Unknown"
Now, show me how far you've understood your lessons!
Input
1. First integer
2. Second integer
3. Third integer
4. Fourth integer
5. Fifth integer
Output
The first five lines will contain message prompts to input the five integers.
The last line contains the appropriate string.
Enter·integer·1:·1
Enter·integer·2:·4
Enter·integer·3:·6
Enter·integer·4:·3
Enter·integer·5:·2
Middle
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
String num[] = Scan.nextLine().trim().split(" ");
int n = Integer.parseInt(num[0]);
int M = n;
int maxindex = 0;
for (int y = 0; y < num.length; y++) {
n = Integer.parseInt(num[y]);
if (n > M) {
M=n;
maxindex = y;
}
}
if (maxindex <= 1) {
System.out.println("Leftmost");
}else
if (maxindex == 2) {
System.out.println("Middle");
}else
if (maxindex >2) {
System.out.println("Rightmost");
}else
{
System.out.println("Unknown");
}
Scan.close();
}
}
Comments
Leave a comment