Answer to Question #306087 in Java | JSP | JSF for linda

Question #306087

Given a positive number, create an array with that number as a 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-04T12:31:29-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