如何查找数组的片段

时间:2014-12-08 20:29:56

标签: java arrays segment

我需要帮助找到如何分割数组以找到每四个值并查看这些值是否超过10.我试图实现.subList但我不确定这是否会在正确的轨道上。以下是我目前所做的工作,所以请提前获得帮助。

import java.util.Scanner;
public class Problem1 {
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        System.out.print( "Enter how many downs there are:");
        int x = sc.nextInt();
        double[] yards = new double [x];
        double num1 = 0;


        for (int i = 0; i < yards.length; i++){
            //System.out.print( (i+1)+ " Enter the quality of the food on a scale from 1-5:");
            System.out.print( "Enter the yards they moved:");
            yards[i] = sc.nextDouble();


                num1 += yards[i];

                if (yards[i] <=0){
                    System.out.print("SAFETY");
                }
                if ( num1 == 100){
                    System.out.print("TOUCHDOWN");
                    System.exit(0);
                    //System.out.print( num1 );
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

for(int i = 0; i < array.length; i++){
    if(i % 4 == 0){
        if(array[i] > 10){
            //Whatever you want to do here
        }
    }
}

现在让我在这里解释一切:

  • 你有for循环遍历数组。
  • 您检查i除以4 是否有余数(%除以2个数字并输出余数)
  • 如果数字(i)没有余数,则检查array[i]是否大于10。
  • 然后,如果array[i]确实发生在其中一个&#34;第四&#34;你正在寻找的老虎机。

同样,您可以说if(i % 4 == 0 && array[i] > 10)然后您不会嵌套if语句。

答案 1 :(得分:0)

for (int i = 0; i < yards.length) {
    if (i + 4 < yards.length){
        sum = yards[i] + yards[i + 1] + yards[i + 2] + yards[i + 3];
        if (sum > 10) {
            // do something if the sum of the 4 numbers is larger then 10
        } else {
            // do something if its smaller then 10
        }
     } else {
         // do something if there is less than 4 remaining numbers in the array.
         // handle the last 3, 2, or 1 numbers in the array
     }
}

从我对你的代码和你问的内容的理解。