You have to reassign it to your variable (or to a new one):
input = input.replaceAll(" ", "");
Strings are immutable which means they cannot be altered. What replaceAll()
does is create a new string. Therefore in order to use it, you have to assign it to a variable.
The reason you are only seeing Hello
is because you're using scanner.next()
instead of scanner.nextLine()
.
The former will only take the first token until the delimiter (standard: whitespace) is reached. The latter will consider an endline character (in windows: \r\n
, enter) as its delimiter.
Your working code looks like this:
public static void main (String [] args) {
String input;
Scanner console = new Scanner(System.in);
System.out.print("enter text: ");
input = console.nextLine(); // Change here
System.out.println();
input = input.replaceAll(" ", ""); // Change here
System.out.println(input);
}