D. Lark D. Lark - 1 year ago 38
Java Question

Adding text to a printed array?

I'm a student just starting out in Java; I get hung up on seemingly easy concepts and have had trouble finding the answer to this despite a lot of googling. The assignment asks to:

  • Prompt the user to enter the number of people

  • Create a String array of the given size

  • Prompt the user for the name of each person

  • Put each name in the String array you created

  • Use a Java for-each to print each name with the length of the name

The output should look something like:

  • "Person 1 is named Andrew, and their name is 6 characters long"

This is what I currently have coded.

System.out.print("Hello. Please enter the number of people: ");

int people = scan.nextInt();

String[] myPeople = new String[people + 1];

System.out.println("Enter the name of each person:");
for(int i = 0; i < myPeople.length; i++)

myPeople[i] = scan.nextLine();

for(String peoples : myPeople)

As it stands right now, the program can collect input from the user, put it into an array, and then print the array back out.

Am I approaching this the wrong way? I can't think of how I would modify the last For to not just print all the names, and instead print out each one with the "Person X is named ... ", their name, and then the description of how many characters long their name is.

Answer Source

You are doing good. In last for loop you can just do something like:

int personNumber = 0;
for(String people: myPeople)
System.out.println(String.format("Person %d is named %s, and their name is %d characters long", personNumber + 1, people, people.length());

And one thing I've noticed - why are you instantiating array using new String[people + 1]? Why this extra one person? Arrays indexes are numered from 0, so new String[5] would give you array of 5 persons.