【问题标题】:for loop print - as many as the word length?for 循环打印 - 与字长一样多?
【发布时间】:2013-11-18 14:54:37
【问题描述】:

如何打印出与单词长度相同的破折号“-”? 我使用了 for 循环,但只有 1 个破折号。

    for(int i=0; i<secretWordLen; i++) theOutput = "-";

主要:

public String processInput(String theInput) {
    String theOutput = null;

    String str1 = new String(words[currentJoke]);
    int secretWordLen = str1.length();

    if (state == WAITING) {
        theOutput = "Connection established.. Want to play a game? 1. (yes/no)";
        state = SENTKNOCKKNOCK;
    } else if (state == SENTKNOCKKNOCK) {
        if (theInput.equalsIgnoreCase("yes")) {
            //theOutput = clues[currentJoke];
            //theOutput = words[currentJoke];
            for(int i=0; i<secretWordLen; i++) theOutput = "-";
            state = SENTCLUE;

【问题讨论】:

标签: java string


【解决方案1】:

使用StringBuilder:

StringBuilder builder = new StringBuilder();
for(int i=0; i<secretWordLen; i++) {
    builder.append('-');
}
theOutput = builder.toString();

如果您在theOutput 中想要的只是一系列破折号,则可以这样做。如果你想之前有一些东西,只需在附加破折号之前使用 builder.append()。

+= 的解决方案也可以工作(当然,之前需要将 theOutput 初始化为某些东西,所以你不要附加到 null)。在幕后,Java 会将任何+= 指令转换为使用StringBuilder 的代码。直接使用它可以更清楚地了解正在发生的事情,在这种情况下效率更高,并且通常是了解如何在 Java 中操作 String 的好东西。

【讨论】:

  • 谢谢,是的,如果没有初始化,+= 解决方案将按照您提到的那样附加 null。
【解决方案2】:

您在每次迭代中都覆盖了您的输出变量。

改成:

theOutput += "-";

【讨论】:

    【解决方案3】:

    theOutput += "-";代替theOutput = "-";

    【讨论】:

      【解决方案4】:

      你必须每次都追加结果。

      for(int i=0; i<secretWordLen; i++)
       theOutput += "-"; 
      

      当你写 theOutput += "-"; 这是

         theOutput = theOutput +"-";  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多