-1

I need help finding how to segment an array to find every four values and see if those values go over 10. I tried to implement .subList but I'm not sure if that would be on the right track. Below is what i currently have done so far so thanks for help in advance.

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 );
                }
            }
        }
    }
}
MisterEh
  • 1
  • 1

2 Answers2

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

Now let me explain everything here:

  • You have the for loop their to cycle through the array.
  • You check if i divided by 4 has a remainder (the % divides the 2 numbers and outputs the remainder)
  • If the number (i) has no remainder, then you check if array[i] is greater than 10.
  • Then whatever you want to happen happens if array[i] does happen to be on one of the "4th" slots you were looking for.

Similarly, you could say if(i % 4 == 0 && array[i] > 10) then you'd just not nest the if statement.

Nicholas Eason
  • 290
  • 4
  • 13
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
     }
}

From what I understood from your code and what you asked.

Code Whisperer
  • 1,041
  • 8
  • 16