为什么我不能在 Java 中删除空格? [英] Why can't I Remove WhiteSpaces in Java?

查看:46
本文介绍了为什么我不能在 Java 中删除空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拼命地试图从字符串中删除空格(那晚我希望能够转换为 int),但我似乎无法把它做好.

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)

你能告诉我,我做错了什么吗?PS:我也试过 \W" 和 \S"

Can you please tell me,what it is that i'm doing wrong? PS:I've tried \W" and \S" too

推荐答案

替换

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

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

它会起作用,因为字符串是不可变的,所以 replaceAll() 不会改变你的字符串对象,它会返回一个新的.因此,您将变量 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","");

此外,您应该尝试遵循 Java 命名约定,并让您的字段和变量以小写字母开头.

Also, you should try to follow the Java naming conventions, and have your fields and variables start with a lowercase letters.

而且,你也可以替换

if(GamePlay.GameStart == true) {

if(GamePlay.GameStart) {

因为在您的版本中,您将 GamePlay.GameStart 的值与 true 进行比较,并且仅在评估结果为 if 时才执行 if 块code>true,而在我的版本中,ìf 块在 GamePlay.GameStarttrue 时执行(尽管编译器可能无论如何都会优化它).

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).

另外,你也可以替换

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

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

因为,我认为这很明显.

because, well I think it's obvious.

这篇关于为什么我不能在 Java 中删除空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆