Given a positive number, create an array with that number as the size and populate it with the items/names provided. Additionally, the program should print out the longest name in the array.
Sample Run1
3
Apple
Banana
Kiwi
Output1: Banana is the longest name
import java.util.*;
class App {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter size of array: ");
int size = in.nextInt();
String names[] = new String[size];
in.nextLine();
for (int i = 0; i < size; i++) {
System.out.print("Enter name " + (i + 1) + ": ");
names[i] = in.nextLine();
}
int longestNameIndex = 0;
String longestName = names[0];
for (int i = 1; i < size; i++) {
if (names[i].length() > longestName.length()) {
longestName = names[i];
longestNameIndex = i;
}
}
System.out.print(names[longestNameIndex] + " is the longest name");
in.close();
}
}
Comments
Leave a comment