Why can't I Remove WhiteSpaces in Java?

2019-03-03 18:43发布

问题:

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

回答1:

replace

input.replaceAll("\\s","");

with

input = input.replaceAll("\\s","");

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 variable input to the string returned by input.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

if(GamePlay.GameStart == true) {

with

if(GamePlay.GameStart) {

because in your version you compare the value of GamePlay.GameStart with true, and only execute the if block if that evaluation is true, whereas in my version, the ìf block is executed if GamePlay.GameStart is true (although the compiler probably optimizes it away anyway).

On another note, you can also replace

if (input.equals("Quit") || input.equals("quit")){

with

if (input.equalsIgnoreCase("Quit")) {

because, well I think it's obvious.



回答2:

Strings are immutable. You need to assign your result of the newly created String returned by replaceAll:

input = input.replaceAll("\\s","");


回答3:

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:

input = input.replaceAll("\\s","");


回答4:

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:

input=input.replaceAll("\\s","");

If you wish, you can have assistant plugins to help you with such bugs, such as findBugs and codePro.