![](/img/trans.png)
[英]How to add integers from one two dimensional array and create a new two dimensional array
[英]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.