Answer to Question #308473 in Java | JSP | JSF for guru

Question #308473

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-09T06:39:40-0500


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();
	}
}

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