简体   繁体   English

遍历数组的Java代码

[英]java code looping through an array

why is my code here not working im trying to print out every second number in the sequence as hello 为什么我的代码在这里不能正常工作,我试图将序列中的第二个数字打印为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");
        }
    }
}

To print every second element, print inside the condition as shown below: 要打印第二个元素,请在如下所示的条件内打印:

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

You missed the curly braces of for loop. 您错过了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");
            }
        }
        }
    }

use this 用这个

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");
        }
    }
}

If you want to print every second number as hello, you can try below looping : 如果您想将第二个数字打印为hello,可以尝试以下循环:

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

It's because the 'for' loop is missing the curly braces thus only one line below it is printed. 这是因为“ for”循环缺少花括号,因此仅打印了下面的一行。 If you want more than one statements to be executed in the 'for' loop, add a curly brace before the statements start and after your block of statements end. 如果要在“ for”循环中执行多个语句,请在语句开始之前和语句块结束之后添加大括号。 I believe your code does currently print one Hello though, doesn't it? 我相信您的代码目前确实可以打印一张Hello,不是吗? That is because when the if statement runs the value of i is 10 thus fulfilling the if condition. 这是因为当if语句运行时,i的值为10,因此满足if条件。

Your missing a curly brace at the start of your for loop. 您在for循环开始时缺少花括号。

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

should be 应该

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

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

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