Search code examples
javajava.util.scannerwhitespacejoptionpane

Difference between String loaded from Scanner and JOptionPane


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


Solution

  • 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.