Why can't I Remove WhiteSpaces in Java?

2019-03-03 18:34发布

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

4条回答
Summer. ? 凉城
2楼-- · 2019-03-03 19:13

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

input = input.replaceAll("\\s","");
查看更多
放荡不羁爱自由
3楼-- · 2019-03-03 19:14

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楼-- · 2019-03-03 19:17

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.

查看更多
姐就是有狂的资本
5楼-- · 2019-03-03 19:29

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.

查看更多
登录 后发表回答