簡體   English   中英

遍歷數組的Java代碼

[英]java code looping through an array

為什么我的代碼在這里不能正常工作,我試圖將序列中的第二個數字打印為hello

public class Generalizations {
    public static void main(String[] args) {


        for(int i=0;i<10;i++)
            System.out.println(i);
        if (i%2==0){
            System.out.println("hello");
        }
    }
}

要打印第二個元素,請在如下所示的條件內打印:

for(int i=0;i<10;i++) {//esnure the brace here       
   if (i%2 == 0) {
       System.out.println(i);//prints every second element
   }
}

您錯過了for循環的花括號。

public class Generalizations {
    public static void main(String[] args) {


        for(int i=0;i<10;i++){
            System.out.println(i);
            if (i%2==0){
                System.out.println("hello");
            }
        }
        }
    }

用這個

public class Generalizations {
public static void main(String[] args) {


    for(int i=0;i<10;i++){
        System.out.println(i);
        if (i%2==0){
            System.out.println("hello");
        }
    }
}

如果您想將第二個數字打印為hello,可以嘗試以下循環:

for(int i=1;i<=10;i++){            
        if (i%2==0){
            System.out.println("hello");
        }else{
            System.out.println(i);
        }
    }

這是因為“ for”循環缺少花括號,因此僅打印了下面的一行。 如果要在“ for”循環中執行多個語句,請在語句開始之前和語句塊結束之后添加大括號。 我相信您的代碼目前確實可以打印一張Hello,不是嗎? 這是因為當if語句運行時,i的值為10,因此滿足if條件。

您在for循環開始時缺少花括號。

for(int i=0;i<10;i++)

應該

for(int i=0;i<10;i++){

暫無
暫無

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

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