3

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;
} 
Dave Carruthers
  • 502
  • 1
  • 7
  • 25
  • Think you mistyped but it should be `scanner.hasNext()` – Alexis C. Nov 25 '13 at 11:03
  • That's a typo, otherwise his program won't compile. – Maroun Nov 25 '13 at 11:05
  • That shouldn't loop forever. Are you definitely sure it's `readString()` that's getting stuck? Show us more code, please. – kviiri Nov 25 '13 at 11:08
  • I enter "John Smith" on one line. Hit enter the cursor jumps to the next line and keeps reading input, the scanner never exits. – Dave Carruthers Nov 25 '13 at 11:11
  • Marked as duplicate however the solutions seem to differ. The scanner object was used earlier in the code to first read some ints. Later I tried to use the same scanner .nextLine method to read in names. The first time I called .nextLine it was coming back as an empty string. Still not sure why but using a new instance of scanner has solved the problem. Therefore the "duplicate" solution would not have worked in this case. – Dave Carruthers Nov 25 '13 at 17:47

2 Answers2

3

Use nextLine() method instead of next()

Do like this

private String readString()
{
    Scanner scanner = new Scanner(System.in);
    return scanner.nextLine();
} 
Denim Datta
  • 3,528
  • 3
  • 25
  • 53
Prabhakaran Ramaswamy
  • 23,910
  • 10
  • 51
  • 62
  • having a `readString()` method is a bit overkill since `scanner.nextLine();` is only one line, don't you think? – Sionnach733 Nov 25 '13 at 11:13
  • 1
    @Sionnach733 thanks for your suggestion and i agree on this but i don't want confuse OP's – Prabhakaran Ramaswamy Nov 25 '13 at 11:28
  • I was using one instance of scanner to read in multiple lines from the console. Using scanner.nextLine() was returning an empty string for the first line then working correctly afterwards. The soloution above has solved the problem. Create a new instance for each read it functions correctly. Thanks to all for your help. – Dave Carruthers Nov 25 '13 at 12:06
  • @DaveCarruthers you are welcome. – Prabhakaran Ramaswamy Nov 25 '13 at 12:09
1

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();
}
Ruchira Gayan Ranaweera
  • 32,406
  • 16
  • 66
  • 105