[英]How can I use a variable from another class in Java
Please help me how can I use a variable from deviation_2DArray.java into NBC.java , in NBC.java I want to average b[i]
by d[i][j]
and c[j]
请帮助我,如何使用从偏差 _2DArray.java到NBC.java的变量,在NBC.java中,我想将d[i][j]
和c[j]
b[i]
平均
Example: 例:
b[1]=avg (d[1][1]+d[1][2]+.....+d[1][5])
Thanks in advance. 提前致谢。
2DArray.java 2DArray.java
public class 2DArray {
public static void main(String[] args) {
double[][] d = new double[6][4];
double[][] e = {
{}, {
0.0, 0.6, 0.0, 0.0
}, {
0.0, 0.2, 0.5, 0.1
}, {
0.0, 0.2, 0.5, 0.4
}, {
0.0, 0.2, 0.5, 0.7
}, {
0.0, 0.0, 0.0, 0.9
}
};
double[] avg = new double[4];
double[] sum = new double[4];
int i, j, k;
//average of column
for (j = 1; j < e[1].length; j++) {
for (i = 1; i < e.length; i++)
System.out.println("e[" + i + "][" + j + "] = " + e[i][j]);
}
for (j = 1; j < e[1].length; j++) {
sum[j] = 0.0;
k = 0;
for (i = 1; i < e.length; i++)
if (e[i][j] > 0.0) {
sum[j] += e[i][j];
k++;
}
avg[j] = sum[j] / k;
System.out.println("Average of j[" + j + "] = " + avg[j]);
}
for (j = 1; j < e[1].length; j++) {
for (i = 1; i < e.length; i++)
if (e[i][j] > 0.0) {
d[i][j] = Math.abs(e[i][j] - avg[j]);
System.out.println("d[" + i + "][" + j + "] = " + d[i][j]);
}
}
}
}
NBC.java NBC.java
public class NBC {
public static void main(String[] args) {
double[] b = new double[6];
double[] c = new double[4];
int count;
b[i] = d[i][j] / count;
}
}
我将它恢复为一个简单的词: getters 。
You need to create class-level fields in the 2DArray
class and provide getter methods to those fields. 您需要在2DArray
类中创建类级别的字段,并为这些字段提供getter方法。 Then NBC
would need to have an instance of 2DArray
unless you made those fields / getters static. 然后,除非您将这些字段/ 2DArray
否则NBC
将需要具有2DArray
的实例。
Currently your d
variable in 2DArray
is only in the scope of the main method, therefore just providing a getter won't solve the problem because d
only has scope in the method. 当前,您在2DArray
的d
变量仅在main方法的范围内,因此仅提供getter将无法解决问题,因为d
在方法中仅具有范围。
Also, each class has its own main
method. 而且,每个类都有其自己的main
方法。 You can only execute one main
per application. 每个应用程序只能执行一个main
。 So how is your flow of control getting from 2DArray
to NBC
? 那么,您的控制流程如何从2DArray
转到NBC
? If 2DArray
is calling NBC
, then you could pass the array as an argument. 如果2DArray
正在调用NBC
,则可以将数组作为参数传递。
Create a method in the 2DArray something like this: 在2DArray中创建一个类似下面的方法:
public double getElement(int i, int j) {
return d[i][j];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.