Read multiple word strings with java.util.Scanner()

44,548

Solution 1

Use nextLine() method instead of next()

Do like this

private String readString()
{
    Scanner scanner = new Scanner(System.in);
    return scanner.nextLine();
} 

Solution 2

This may help you

public static void main(String[] args) {
    System.out.println("Name: "+getInput());
}

private static String getInput() {
    Scanner scanner = new Scanner(System.in);
    return scanner.nextLine();
}
Share:
44,548
Dave Carruthers
Author by

Dave Carruthers

Full stack web application developer at Aeternum software

Updated on November 09, 2020

Comments

  • Dave Carruthers
    Dave Carruthers over 3 years

    I want to read a full name in from the console using java.util.Scanner() and assign that value to a string.

    for example;

    Type "John Smith" in console. Hit return and String s = "John Smith";

    I tried writing a readString method to do this but its getting loop locked. Does anyone know a soloution?.

    part of my code.

    System.out.println("Name: ");
    String name = readString();
    

    and my broken method.

    private String readString()
    {
        String s ="";
        while(scanner.hasNext())
        s += scanner.next();   
        return s;
    }