0

I am trying to write a java program that prompts the user to enter 5 names. These names need to be stored in an array. Once the 5th name is entered, the program will automatically print the results back to the user. I am having problems getting my scanner working to capture the user's input when they type the name.

This is what I have so far:

Scanner input = new Scanner(System.in);
System.out.println("Enter name 1: ");
String name 1 = input.nextLine();
2
  • 3
    That won't compile as the last line is not even a Java statement. Commented Apr 16, 2014 at 0:50
  • If you clarify the actual issue (error messages and such) we can help you more. With the code provided I pointed out the one issue I saw, but there might be more. Commented Apr 16, 2014 at 0:52

2 Answers 2

2

String name 1 = input.nextLine(); won't work because there is a space between name and 1. It needs to be String name1 = input.nextLine();

Here is a complete example:

String[] names = new String[5];
Scanner in = new Scanner(System.in);

for (int i=1;i<=5;i++) {
    System.out.println("Enter name number " + i + ".");
    names[i] = in.nextLine();
}

System.out.println("Names entered:");

for (int i=1;i<=5;i++) {
    System.out.println(names[i]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The OP requires an array, as the original question reads (as of 00:52:20 UTC)
1

this is what you are looking for

    String[] names = new String[5];
    Scanner input = new Scanner(System.in);
    for (int i = 0; i < names.length; i++) {
        names[i] = in.nextLine();
    }
    for (String string : names) {
        System.out.println(string);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.