簡體   English   中英

編寫將字符串一次添加到一個字符串的循環

[英]Writing loops that add a string to a string one at a time

我想編寫一個循環以在屏幕上打印雙行(===),一次打印一條(=)。 我對Java還是很陌生,現在正在練習循環。 我希望我的結果看起來像這樣:

     =
     ==
     ===
     ====

等等。

到目前為止,這就是我所擁有的。

    int twoLines = 0;
    while (twoLines < 10)
    { System.out.println("=");
    twoLines = twoLines + 1;
    }

為了一次添加一個“ =”,我需要怎么做?

我知道這對你們大多數人來說都是超級基礎,但是我仍然在弄清楚這些東西。 預先感謝您的任何建議。

關鍵思想是在while循環中的每次迭代后修改要打印的string 這將起作用:

int twoLines = 0;
String string = "=";
while (twoLines < 10)
{ 
    System.out.println(string);
    string = string + "=";
    twoLines = twoLines + 1;
}
int twoLines = 1;

while (twoLines <= 10)
{ 
    int i = 1;
    while(i <= twoLines) {
        System.out.println("=");
        i = i + 1;
    }
    System.out.println(""); // next line
    twoLines = twoLines + 1;
}

您可以使用兩個循環來實現此目的。 內循環打印符號“ =”,外循環打印新行。

    int i=0;
    while (i < 10) {
        int j=0;
        while (j < i){
            System.out.print("=");
            j++;
        }
        //print a new line
        System.out.println("\n");
        i++;
    }

好的,您是否能夠運行此代碼並查看其打印內容?

目前,您的代碼僅每行打印一次“ =”,

System.out.println("=");

永不改變? 每次循環運行時,都會調用此語句,在print語句中使用相同的“ =”。

我們需要一種更改該打印語句的方法,以便每次循環運行時,其打印內容都是不同的。

因此,如果我們將“ =”存儲在變量中並打印該變量,則可以在每次循環運行時向該變量添加另一個“ =”。

int twoLines = 0;
string output = "="

while (twoLines < 10){

    // first print the output
    System.out.println(output);

    // then change the output variable, so that the next loop
    // prints a longer string
    output += "=";

    // then increment the twoLines variable
    twoLines++;
}

線; 輸出+ =“ =”; 是串聯的捷徑。 串聯是將字符串加在一起的過程。 通過使用'+ ='運算符,是說我想將字符串“ =”添加到字符串輸出的末尾。

線; twoLines ++; 是增加變量的另一個小捷徑。 “ ++”運算符將1加到變量中。

簡而言之,您只想看看如何更改打印語句,以反映每次循環運行時要查看的更改。

我不確定您是否要在一行上打印=字符,一次打印一次。 如果真是這樣,那么您可能不想使用system.out.println(因為這在每次調用時都會打印新行)。

首先,請注意,如果上述假設是正確的,那么這可能是以下SO問題的重復: 如何打印到同一行?

就是說,也許這是您要尋找的天真的解決方案:

import java.util.concurrent.TimeUnit;
import java.lang.InterruptedException;

public class OneLine {
    public static void main(String[] args) throws InterruptedException {
        // Prints "="'s to the terminal window, one iteration at a time, 
        // on one line.
        int twoLines = 0;
        while (twoLines < 10) {
            System.out.print("=");
            twoLines = twoLines + 1;
            TimeUnit.MILLISECONDS.sleep(100);
        }
        System.out.println("");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM