Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multiple word strings with java.util.Scanner() [duplicate]

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;
} 
like image 585
Dave Carruthers Avatar asked Nov 24 '25 15:11

Dave Carruthers


2 Answers

Use nextLine() method instead of next()

Do like this

private String readString()
{
    Scanner scanner = new Scanner(System.in);
    return scanner.nextLine();
} 
like image 146
Prabhakaran Ramaswamy Avatar answered Nov 26 '25 03:11

Prabhakaran Ramaswamy


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();
}
like image 23
Ruchira Gayan Ranaweera Avatar answered Nov 26 '25 03:11

Ruchira Gayan Ranaweera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!