-1

I have made this program and I have gotten stuck. When I run it and I have inputs without using spaces it works fine, for example just Bob input in customer input. However, when I enter Bob White, it merges the next two string input directions (as Shown in pic attached) . What am I doing wrong here?

import java.util.*;

public class Blah{

    public static void main(String[] args){ 

        Scanner in = new Scanner(System.in);

        String customerName;
        System.out.println("Enter customer name: ");        
        customerName = in.next(); 

        String customerAddress; 
        System.out.println("Enter customer address: ");         
        customerAddress = in.next();

        String customerPhoneNumber;
        System.out.println("Enter customer phone number: ");            
        customerPhoneNumber = in.next();

        in.close();
    }
}

output

Yahya
  • 9,370
  • 4
  • 26
  • 43
bob brown
  • 11
  • 6

2 Answers2

1

You need to read the entire line using nextLine() method then trim it from leading and trailing whitespace using trim() method.

customerName = in.nextLine().trim();
customerAddress = in.next().trim();
customerPhoneNumber = in.next().trim();
Yahya
  • 9,370
  • 4
  • 26
  • 43
1

Thats because the Scanner#next method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine

Try using nextLine() method instead with trem() method

customerName = in.nextLine().trim();
Fady Saad
  • 1,133
  • 7
  • 13