Write a JAVA Program that would: Allow user to enter the size and element of a string array. Display the longest string found in the array.
import java.util.Scanner;
import java.util.stream.Stream;
import static java.util.Comparator.comparingInt;
public class ArrayInputExample1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int numberOfElements = scanner.nextInt();
String[] arrayOfStrings = new String[numberOfElements];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < numberOfElements; i++) {
arrayOfStrings[i] = scanner.next();
}
System.out.print("The longest string in the array is: " + Stream.of(arrayOfStrings).max(comparingInt(String::length)).orElse("Cannot find the longest one"));
}
}
Comments
Leave a comment