String s= "20 30 -60 100 50 ";
Then the second largest number will be 50.
// If you don't want to use Array.sort()
public class Example {
public static void main(String[] args) {
String s= "20 30 -60 100 50 ";
String[] parts = s.split(" ");
int[] numbers = new int[parts.length];
for(int i=0;i
numbers[i] = Integer.parseInt(parts[i]);
}
int largest = numbers[0];
int second = numbers[0];
for(int i=1;i
if(numbers[i] > largest){
largest=numbers[i];
} else {
second=numbers[i];
}
}
for(int i=0;i
if(numbers[i]>second){
if(numbers[i]
second=numbers[i];
}
}
}
System.out.println("String: " + s);
System.out.println("Largest:" + largest);
System.out.println("Second: " + second);
}
}
public static void main(String[] args) {
String s = "20 30 -60 100 50";
//put numbers in an array
String[] stringNums = s.split(" ");
//convert string array to integer array
int[] nums = new int[stringNums.length];
//create for loop to iterate through the strings
for(int i = 0; i < stringNums.length; i++)
nums[i] = Integer.parseInt(stringNums[i]);
//sort array
Arrays.sort(nums);
//print out second to last number in the array
System.out.println(nums[nums.length - 2]);
}
For eg if the given string is like
String s= "20 30 -60 100 50 ";
Then the second largest number will be 50.