簡體   English   中英

帶nextLine條件的While循環

[英]While loop with nextLine condition

我正在為使用數據庫數據的類開發一種方法。 我正在嘗試使用while loop.nextLine為我的數組values[]做一個System.out.println ,我希望有人可以提供一些建議。 我知道還有其他方法可以做到這一點,但我希望不要使用任何其他變量。 如果不可能,我完全理解,但是我認為這里的某人必須知道一種方法。 感謝您的幫助,這是我的方法

    public void query(String table,String... column)
{
    System.out.println("name of table is: " + table);
    System.out.println("column values are: ");

    while(column[].nextLine())
        {
            System.out.println(column.nextLine());
        }

}//end method query()

nextLine()Scanner的方法,而不是String的方法。 如果您有一個String數組,則可以使用一個(增強的) for循環在它們上循環:

public void query(String table, String... column) {
    System.out.println("name of table is: " + table);
    System.out.println("column values are: ");

    for (Strinc c : column) {
        System.out.println(c);
    }
}

您可以使用增強型for (也稱為for-each )循環:

for (String s : column) {
    System.out.println(s);
}

或正常的for循環:

for (int i = 0; i < column.length; i++) {
    System.out.println(column[i]);
}

如果您使用一段while ,則必須保留索引計數:

int i = 0;
while (i < column.length) {
    System.out.println(column[i]);
    i++;
}

注意:

請記住, column是一個數組: String[] column

nextLine()不是數組的方法。 不僅如此,您還錯誤地使用了它。 您應該這樣做(如果存在這些方法): while (column.hasNextLine())

假設您要使用while循環來打印String數組:

int i = 0;
while(i < column.length)
{
    System.out.println(column[i]);
    i++; // increment the index
}

或者,您可以使用for-each循環(或“ enhanced-for”循環,無論其被稱為):

for (String c : column) {
    System.out.println(c);
}

甚至是經典的for循環:

for (int i = 0; i < column.length; i++) {
    System.out.println(column[i]);
}

暫無
暫無

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

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