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.
import java.util.Scanner;
public class Program {
public static String isName(){
System.out.print("Enter a name: ");
Scanner scaner = new Scanner(System.in);
String str = scaner.nextLine();
if (str.substring(0,1).equals(str.substring(0,1).toLowerCase())){
System.out.print("It's not a name ");
str = isName();
}
return str;
}
public static void main(String[]args) {
System.out.print("Enter a number of elements: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String arrayName[] = new String[n];
String name = null;
for (int i = 0; i < n; i++){
arrayName[i] = isName();
}
String maxLenghtName = arrayName[0];
System.out.print("The longest name in the array: ");
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (maxLenghtName.length() < arrayName[j].length()){
maxLenghtName = arrayName[j];
}
}
if(maxLenghtName.length() == arrayName[i].length()){
System.out.print(arrayName[i] + " ");
}
}
}
}
Comments
Leave a comment