Answer to Question #308091 in Java | JSP | JSF for Chakalaka

Question #308091

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


1
Expert's answer
2022-03-08T13:06:44-0500
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();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS