Java中的数组和if语句

时间:2017-01-22 11:02:16

标签: java arrays

public static void main(String[] args) {
    int array [] = {1,2,3,4,5};
    if (array[] < 4) {
        System.out.println(array[] + "is less than 4");
    }
}

我该如何工作?我想要使​​用数组中的所有数字但是当我这样做时(array [] ...)我必须在[]中加上一个数字。

8 个答案:

答案 0 :(得分:1)

如果要验证数组中的每个元素,可以使用for循环来增加索引:

for (int i = 0; i < array.length; i++) {
    if (array[i] < 4) {
        System.out.println(array[i] + " is less than 4");
    }
}

答案 1 :(得分:1)

作为@shmosel的替代方案,您还可以为每个循环使用a:

GameScene

答案 2 :(得分:0)

您试图立即比较完整数组,这是无效的。

您需要迭代数组并单独比较每个数组元素。

for (int i=0; i<array.length; i++) 
{
   if (array[i] < 4) {
       System.out.println(array[i] + " is less than 4");
   }
}

答案 3 :(得分:0)

for loop

中移动以下代码
if(array[]<4){
            System.out.println(array[] + "is less than 4");

喜欢这个

public static void main(String[] args) {
        int array []= {1,2,3,4,5};
        for (int i = 0; i < array.length; i++) {
        if(array[i]<4){
            System.out.println(array[i] + "is less than 4");
        }
    }
  }

或者,更简单的解决方案可能是使用enhanced for-loop

public static void main(String[] args) {
        int array []= {1,2,3,4,5};
        for (int value : array) {
        if(value<4){
            System.out.println(value + "is less than 4");
        }
    }
  }

答案 4 :(得分:0)

public static void main(String[] args) {
        int array []= {1,2,3,4,5};

           for (int i = 0; i < array.length; i++) {
           if(array[i]<4){
         System.out.println(myList[i] + " ");
      }
    }
    }
}

答案 5 :(得分:0)

java零索引中的数组所以第一个索引以0开头,arr [0]这是你如何使用方括号和你想要的索引访问数组。

for the array over the array:

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

更多阅读:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

答案 6 :(得分:0)

其他人已经回答了你的问题。我想补充一些额外的信息。如果你想学习Java,你应该熟悉Java 8.在Java 8中它是:

public static void main(String[] args)
{
    int array[] = {1,2,3,4,5};
    Arrays.stream(array).filter(i -> i < 4).forEach(out -> System.out.println(out + " is less than 4"));
}

答案 7 :(得分:-1)

您已定义了元素数组,如下所示: [1,2,3,4,5]。在数组中,项目位于0到4的位置,这意味着您有:

Array[0] = 1
Array[1] = 2
Array[2] = 3
Array[3] = 4
Array[4] = 5

您应该使用从0到4的循环来访问所有元素,例如:

public static void main(String[] args) {
        int array []= {1,2,3,4,5};
   for(int i=0; i<array.length); i++){
        if(array[i]<4){
            System.out.println(array[i] + " is less than 4");
        }
   }
}

这将进行5次迭代,并且“i”的值将增加1直到它达到值5,然后循环将结束(条件是i&lt; array.length)。它将产生输出:

1 is less than 4
2 is less than 4
3 is less than 4