Issue
So I'm trying to read all the input from one line, using scanner, then take the values and find the second largest. I would use an array BUT I am not allowed. You are supposed to enter 10 integers, hit enter and evaluate them.
10 20 30 40 50 60 70 80 90 100 ENTER
Second highest number is: 90
I can't manage to solve it at all. It should be easy but I have no idea.
public class SecondLargest {
public static void main(String[] args) {
{
int largest = 0;
int secondLargest = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter integers: ");
int numbers = sc.nextInt();
largest = numbers;
while (sc.hasNextInt()) {
if (numbers > largest) {
secondLargest = largest;
largest = numbers;
} else if (numbers > secondLargest) {
secondLargest = numbers;
}
}
System.out.println("Second largest number is: " + secondLargest);
sc.close();
}
}
Solution
Start with assigning the first scanned integer to largest
and secondLargest
variables and then process the remaining nine integers in a loop as follows:
num = sc.nextInt();
if (num > largest) {
secondLargest = largest;
largest = num;
}
Demo:
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 10 integers separated by single spaces: ");
// Scan the first integer and assign it to largest and secondLargest
int num = sc.nextInt();
int largest = num;
int secondLargest = largest;
// Input 9 more integers
for (int i = 1; i < 10; i++) {
num = sc.nextInt();
if (num > largest) {
secondLargest = largest;
largest = num;
}
}
System.out.println("The second largest number is: " + secondLargest);
}
}
A sample run:
Enter 10 integers separated by single spaces: 10 23 4 12 80 45 78 90 105 7
The second largest number is: 90
Note: This is just a sample program assuming that the input is in the correct format. I leave it to you to work on how to deal with the wrong input. It will be a good exercise for you.
Answered By - Arvind Kumar Avinash
Answer Checked By - Candace Johnson (JavaFixing Volunteer)