简体   繁体   English

for loop print - 与单词长度一样多?

[英]for loop print - as many as the word length?

How can I print out dashes "-" in the same length as the word length? 如何以与字长相同的长度打印短划线“ - ”? I used for-loop but only got 1 dash. 我使用for-loop但只有1个破折号。

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

Main: 主要:

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;

Use StringBuilder : 使用StringBuilder

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

This will do if all you want in theOutput is the series of dashes. 如果在theOutput你想要的theOutput一系列破折号, theOutput了。 If you want to have something before, just use builder.append() before appending the dashes. 如果你想拥有一些东西,只需在附加破折号之前使用builder.append()。

The solution with += would work too (but needs theOutput to be initialized to something before, of course, so you don't append to null ). 通过该解决方案+=将工作太(但需要theOutput之前被初始化的东西,当然,这样你就不会追加到null )。 Behind the scenes, Java will transform any += instruction into a code that uses StringBuilder . 在幕后,Java会将任何+=指令转换为使用StringBuilder的代码。 Using it directly makes it more clear what is happening, is more efficient in this case, and is in general a good thing to learn about how String are manipulated in Java. 直接使用它可以更清楚地了解正在发生的事情,在这种情况下更有效,并且了解如何在Java中操作String通常是一件好事。

You are overwriting your output-variable in each iteration. 您将在每次迭代中覆盖输出变量。

Change it to: 将其更改为:

theOutput += "-";

instead of theOutput = "-"; 而不是theOutput = "-"; use theOutput += "-"; 使用theOutput += "-";

You have to append the result each time. 你必须每次追加结果。

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

When you write theOutput += "-"; 当你写出theOutput += "-"; that's the shorthand of 这是简写

   theOutput = theOutput +"-";  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM