0

why is x.replaceAll("\\s+","") is removing the first space and everything after it? if x was originally a a after doing replaceAll() and printing x, it only prints a not aa.

this is part of a larger project, but for testing purposes I tried it separately on a new java main file and still does the same thing this is the full complete program:

import java.util.*;
public class test {
    public static void main (String args[]){
        Scanner input = new Scanner(System.in);
        String y = input.next();
        String x = y.replaceAll("\\s+","");
        System.out.println(x);      
}

}
j.doe
  • 13
  • 6

2 Answers2

2

By default Scanner uses one or more whitespaces as delimiter, and next() returns only one token between delimiters. So in case of input like foo bar baz next() will return foo another invocation of next() will return baz and another one baz.

If you wan to read entire line use nextLine() but be careful when using it right after other nextXyz() methods.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
0

Ok . Try this:

public static void main (String[] args) throws java.lang.Exception
    {
        Scanner input = new Scanner(System.in);
        String y = input.nextLine();
        String x = y.replaceAll("\\s+","");
        System.out.println(x); 
    }

Use nextLine to get whole string.

SomeDude
  • 7,432
  • 4
  • 19
  • 33