How to create a two-dimensional array from two one-dimensional arrays and perform calculations

advertisements

I have a question on how to create a two dimensional array from two one dimensional arrays and perform calculations. In my case, the program that I have written has two syntax errors when I try to create a two dimensional array from the two one dimensional arrays using two for loops. The first for loop has a syntax error saying non-static variable angle cannot be referenced from a static context and the second for loop has a syntax error saying package velocity does not exist but I already defined it above. How can I fix this? Any help will be greatly appreciated. Below is my code:

public class Catapult {

int velociy[] = {45, 67, 77, 89, 90, 56, 100};
double angle[] = {Math.toRadians(10), Math.toRadians(20), Math.toRadians(25),
Math.toRadians(30), Math.toRadians(35), Math.toRadians(40)};

public static void calculations(int velocity[], int angle[]){
    for(int i = 0; i < velocity.length; i++){
        double answer = velocity[i] * Math.sin(angle[i]) / 9.8;
    }
}

public static void display(){
    for(int i = 0; i < angle.length; i++){
        for(int j = 0; j < velocity.length; j++){
            System.out.println(// how can I make a two dimensional array
                    // from two one dimensional arrays?
            );
        }
        System.out.println();
    }
}
}


I notice that your array of velocities and your array of angles don't have the same length. So I assume you are actually trying to combine every velocity with every angle in your calculation, to give a 2D result; instead of just combining them pairwise. This is how I would do it.

public static void main(String[] args) {
    int[] velocity = {45, 67, 77, 89, 90, 56, 100};
    double[] angle = {Math.toRadians(10), Math.toRadians(20), Math.toRadians(25),
            Math.toRadians(30), Math.toRadians(35), Math.toRadians(40)};

    double[][] result = new double[velocity.length][angle.length];

    for (int i = 0; i < velocity.length; i++ ) {
        for (int j = 0; j < angle.length; j++ ) {
            result[i][j] = velocity[i] * Math.sin(angle[j]) / 9.8;
        }
    }

    System.out.println(Arrays.toString(result));
}