/** * Returns the second largest value in a list of numbers, * where the list is
ID: 3726674 • Letter: #
Question
/**
* Returns the second largest value in a list of numbers,
* where the list is given as a string of text containing integer
* values separated by arbitrary whitespace. Duplicates are allowed, so
* the largest and second largest numbers may be the same; for example,
* given the string "17 137 42 137", the method returns 137.
* The behavior is undefined if the provided string contains any
* non-numeric values or contains fewer than two numbers.
* @param text
* string of text containing at least two numbers separated by whitespace
* @return
* second largest value in the string
*/
public static int findSecondLargest(String text)
{
// TODO
return 0;
}
Explanation / Answer
import java.util.Scanner;
import javax.rmi.ssl.SslRMIClientSocketFactory;
public class SecondLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String numbers;
System.out.println("Enter number in a single line seperated by spaces: ");
numbers = sc.nextLine();
System.out.println(" The second largest number is "+ findSecondLargest(numbers));
}
public static int findSecondLargest(String text)
{
// TODO
int largest = -1, secondLargest = -1;
String arr[] = text.split(" ");
if(arr.length >= 2) {
largest = Integer.parseInt(arr[0]);
for(int i=1; i<arr.length;i++) {
if(largest <= Integer.parseInt(arr[i])) {
secondLargest = largest;
largest = Integer.parseInt(arr[i]);
}
}
return secondLargest;
}
return -1;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.