1
class Property {
    public static void main (String[] args) {
        Scanner input = new Scanner(System.in);
        String[] rooms = new String[15];

        System.out.println("How many rooms? ");
        int roomLimit = input.nextInt();

        for (int i = 0; i < roomLimit; i++) {
            System.out.println("Enter room name " + (i + 1));
            rooms[i] = input.next();
        }

When I enter room names that are single words like, 'double, single, master, etc.', the list of room names displays fine. But when I enter room names with more than one word, only the first word is listed, and the second word of the first room name automatically becomes the second room name as shown below.

How many rooms? 
4
Enter room 1
Double Duluxe 
Enter room 2
Enter room 3
Couple Golden
Enter room 4

List of Chosen Rooms 
Room 1: Double
Room 2: Duluxe
Room 3: Couple
Room 4: Golden

Process finished with exit code 0
Talendar
  • 1,322
  • 10
  • 20
David N
  • 19
  • 3
  • Use `nextLine()`. And for your next question see: [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045) (my suggestion on that problem: https://stackoverflow.com/a/39949330) – Pshemo Feb 06 '21 at 02:36

1 Answers1

0

Just use the method Scanner.nextLine() instead of using Scanner.next().

Scanner.next() , according to the docs:

Finds and returns the next complete token from this scanner.

This means that it will only read the first word (the token, in your case). Scanner.nextLine(), on the other hand (docs):

(...) returns the rest of the current line, excluding any line separator at the end.

Which means it will read the entire line.

Your code will look like this after the change:

// ...
System.out.println("Enter room name " + (i + 1));
rooms[i] = input.nextLine();
// ...
Talendar
  • 1,322
  • 10
  • 20
  • 1
    Generally suggestion to use `nextLine()` is correct. Now we are waiting for OP to complain about first `nextLine()` in loop skipping user data / returning empty string (notice what method was called on Scanner before loop). – Pshemo Feb 06 '21 at 02:32
  • 1
    That makes sense. I get it now. Thank you – David N Feb 06 '21 at 02:55