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 Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of items: ");
int size = keyboard.nextInt();
String names[] = new String[size];
keyboard.nextLine();
for (int i = 0; i < size; i++) {
System.out.print("Enter item " + (i + 1) + ": ");
names[i] = keyboard.nextLine();
}
int index = 0;
String longestName = names[0];
for (int i = 1; i < size; i++) {
if (names[i].length() > longestName.length()) {
longestName = names[i];
index = i;
}
}
System.out.print(names[index] + " is the longest name");
keyboard.close();
}
}
Comments
Leave a comment