0

I am wondering what's the difference between String object loaded from Scanner.next() and JOprionPane.showInputDialog("text");

I had a problem in my small program, when I used Scanner:

 Scanner sc = new Scanner(System.in);
 String s = sc.next();
 s = s.replaceAll("\\s+", "");

and I wrote, let's say "Dami an" the result was "Dami"

but when I loaded String using JOptionPane:

    String s = JOptionPane.showInputDialog("Text");
    s = s.replaceAll("\\s+", "");

the result was (as I expected in the previous example) "Damian".

Why the results are different?

Thanks for help :)

Best regards :D

DamDev
  • 73
  • 1
  • 1
  • 7

2 Answers2

1

sc.next() only returns a single token, so it only gets the Dami the first time you call it, not Dami an. You'd get an if you called sc.next() again.

Use sc.nextLine() if you want to get the whole line at once.

Andy Turner
  • 122,430
  • 10
  • 138
  • 216
1

Because Scanner.next() method fetches next token which is Dami, the an is the second token just after Dami.

If you want whole line to be read the most efficient(performance-wise) way you might want to use:

try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
String s = br.readLine();
}catch(IOException e){e.printStackTrace();}
Yoda
  • 15,011
  • 59
  • 173
  • 291
  • Or Scanner#nextLine depending on your needs – MadProgrammer Jan 06 '16 at 23:14
  • @MadProgrammer Is `Scanner.nextLine()` faster in any situation? I read that it has buffer under it but when I used scanner to read numbers into arrray and measured time it was always slower than `BufferedReader.nextLine()` and then `String.split()` and then `Integer.parseInt()` which seams weird. – Yoda Jan 06 '16 at 23:20
  • This isn't a time critical question, the simplest solution to solve the op's problem is to use nextLine. Would I use Scanner? Probably not, but it wasn't available when I started with Java (ps I'm not complaining about your answer per say, just that in this case, next/nextLine are the differences) – MadProgrammer Jan 06 '16 at 23:30