I'm desperately trying to remove white spaces from a String (that late i want to be able to convert into an int) but i can't seem to get it all right.
String input;
if(GamePlay.GameStart == true){
input = Terminal.askString("Welcome to MASTERMIND! \n Please Give in Your Game Attributes \n");
input.replaceAll("\\s","");
}else
input = Terminal.askString("");
if (input.equals("Quit") || input.equals("quit")){
Quit();
}
else if(GamePlay.GameStart == true){
System.out.println(input); .......(code follows)
Can you please tell me,what it is that i'm doing wrong? PS:I've tried \W" and \S" too
Strings are immutable. You need to assign your result of the newly created
String
returned byreplaceAll
:input.replaceAll("\\s","");
returns a string with the spaces removed. But if you don't keep a reference to it you won't be able to see the result. You probably meant:replace
with
It will work, because strings are immutable, so
replaceAll()
won't change your string object, it will return a new one. So you assign your variableinput
to the string returned byinput.replaceAll("\\s","");
Also, you should try to follow the Java naming conventions, and have your fields and variables start with a lowercase letters.
And, you can also replace
with
because in your version you compare the value of
GamePlay.GameStart
withtrue
, and only execute theif
block if that evaluation istrue
, whereas in my version, theìf
block is executed ifGamePlay.GameStart
istrue
(although the compiler probably optimizes it away anyway).On another note, you can also replace
with
because, well I think it's obvious.
This is a very common mistake for beginners.
As others have mentioned, you need to know that
replaceAll
returns a new string and doesn't change the current one, since strings are immutable in Java.So use:
If you wish, you can have assistant plugins to help you with such bugs, such as findBugs and codePro.