簡體   English   中英

如何從兩個一維數組創建一個二維數組並執行計算

[英]How to create a two dimensional array from two one dimensional arrays and perform calculations

我有一個問題,如何從兩個一維數組創建一個二維數組並執行計算。 就我而言,當我嘗試使用兩個for循環從兩個一維數組創建一個二維數組時,我編寫的程序有兩個語法錯誤。 第一個for循環有一個語法錯誤,說non-static variable angle cannot be referenced from a static context ,第二個for循環有一個語法錯誤package velocity does not exist但是我已經在上面定義了。 我怎樣才能解決這個問題? 任何幫助將不勝感激。 下面是我的代碼:

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

我注意到您的速度陣列和角度陣列的長度不同。 因此,我假設您實際上是在計算中嘗試將每個速度和每個角度組合在一起,以得出2D結果。 而不是將它們成對組合。 這就是我要做的。

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

嘗試這個:

    Integer 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)};
    Object[][] twoDimensionalArray = {velocity, angle};

第一個for循環存在語法錯誤,即無法從靜態上下文引用非靜態可變角度

您必須將angle-Array定義為靜態的:

static double angle[] = {Math.toRadians(10), Math.toRadians(20), Math.toRadians(25), 
Math.toRadians(30), Math.toRadians(35), Math.toRadians(40)};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM