【问题标题】:Using of Loops then If and Else使用循环 then If 和 Else
【发布时间】:2014-06-07 16:07:01
【问题描述】:

我有一个 ToString() 方法需要运行,但需要使用循环而不是 if 和 else 语句。我该怎么做?

public String toString() 
    {

        if (collectedDots == 0)
            return "Player[]"+"("+x+","+Math.abs(y)+")";
        else if (collectedDots == 1)
            return "Player["+"*"+"]"+"("+x+","+Math.abs(y)+")";
        else if (collectedDots == 2)
            return "Player["+"**"+"]"+"("+x+","+Math.abs(y)+")";
        else 
            return "Player["+"***"+"]"+"("+x+","+Math.abs(y)+")";

    }

【问题讨论】:

  • 为什么要在这里使用循环。在这种情况下使用 Switch case 会是更好的选择
  • 我该怎么做?这是关于打印特定数量的字符。考虑一下。毕竟,这是你的功课。
  • @ankhuri switch 并不理想,因为(1)它将collectedDots 的数量限制为您的开关中的最高case,并且(2)它使您重复基本相同连接代码多次。
  • 为了好玩,for(;condition;){statment; break;} 用作 if 语句,但从不需要
  • 首先,使用 Math.abs(y) 的临时值来消除混乱,让您更清楚地看到自己在做什么。

标签: java


【解决方案1】:

您可以使用 switch 代替 if

switch(collectedDots )
{
case 0:        return "Player[]"+"("+x+","+Math.abs(y)+")";
case 1:        return "Player["+"*"+"]"+"("+x+","+Math.abs(y)+")";
case 2:        return "Player["+"**"+"]"+"("+x+","+Math.abs(y)+")";
default:         return "Player["+"***"+"]"+"("+x+","+Math.abs(y)+")";
}

【讨论】:

    【解决方案2】:

    编写一个产生collectedDots星号字符串的循环:

    String asterisks = "";
    // Here is your loop. It iterates "collectedDots" times
    for (int i = 0 ; i != collectedDots ; i++) {
        // Append an asterisk to the string "asterisks"; I assume that you know how to do that
    }
    

    有了asterisks 字符串,toString 的其余部分就变得微不足道了:

    return "Player["+asterisks+"]"+"("+x+","+Math.abs(y)+")";
    

    【讨论】:

    • 在字符串“asterisks”后面加上一个星号;不知道
    • @user3562745 好吧,asterisks = asterisks + "*" 会做到这一点 - 您在代码中使用了字符串连接 +,所以我假设您知道如何将字符附加到字符串。
    • i != collectedDots 不是好的设计。虽然有效,但不如i < collectedDots 清晰。
    • 感谢这真的有帮助
    【解决方案3】:

    花更多时间查看您的输出。

    你的老师在课堂上教过如何打印下面的图案吗?

    (什么都没有)

    一个

    AA

    AAA

    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0; i < 4; i++) {
            System.out.println(stringBuilder.toString());
            stringBuilder.append("*");
        }
    }
    

    【讨论】:

    • 不,我想教那个追加??
    • 这些是str+="*"; 的幕后和高效使用,虽然也可以使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2017-10-28
    • 2021-08-26
    • 2012-10-15
    相关资源
    最近更新 更多