Java 如何在同一类中的另一个方法中访问一个方法?
在我的代码中,是否可以访问方法Java 如何在同一类中的另一个方法中访问一个方法?,java,arrays,methods,Java,Arrays,Methods,在我的代码中,是否可以访问方法calculateSheet()中的方法calculate()?这两个方法在同一个类中 例如,方法calculate(),计算2倍的总和。 我希望方法calculateSheet(),使用此方法为数组工作表[][]中的每个“单元”计算此值 //calculates every cell in the array. public void calculateSheet() { for(int i = 0 ; i < rows ; i++) { //row
calculateSheet()
中的方法calculate()
?这两个方法在同一个类中
例如,方法calculate()
,计算2倍的总和。
我希望方法calculateSheet()
,使用此方法为数组工作表[][]
中的每个“单元”计算此值
//calculates every cell in the array.
public void calculateSheet() {
for(int i = 0 ; i < rows ; i++) { //rows, amount of rows in the array>
for (int j = 0 ; j < cols ; j++) { //cols, amount of colums in the array.
sheet[i] [j].**calculate()** ; //method I want to use in the "calculateSheet" method.
}
}
}
//计算数组中的每个单元格。
public void calculateSheet(){
对于(int i=0;i
对于(int j=0;j
首先,你需要计算你想要做的事情,你必须把它们放在一些变量中
其次,我相信您需要calculate()方法返回结果
假设您的计算方法类似于:
public double calculate(double a, double b){
return a+b;
}
public void calculateSheet() {
double total = 0; //The variable when you going to put the result
for(int i = 0 ; i < rows ; i++) { //rows, amount of rows in the array>
for (int j = 0 ; j < cols ; j++) { //cols, amount of colums in the array.
total += calculate(sheet[i], sheet[j]);
}
}
}
然后你需要做一些类似的事情:
public double calculate(double a, double b){
return a+b;
}
public void calculateSheet() {
double total = 0; //The variable when you going to put the result
for(int i = 0 ; i < rows ; i++) { //rows, amount of rows in the array>
for (int j = 0 ; j < cols ; j++) { //cols, amount of colums in the array.
total += calculate(sheet[i], sheet[j]);
}
}
}
public void calculateSheet(){
double-total=0;//要放入结果时的变量
对于(int i=0;i
对于(int j=0;j
让我们为您制作完整的代码
阶级{
public double calculate(double num1, double num2){
return (num1+num2);
}
public void calculateSheet(int[][] sheet) {
for(int i = 0 ; i < rows ; i++) {
for (int j = 0 ; j < cols ; j++) {
sheet[i] [j] = calculate(i, j);
}
}
}
公共双计算(双num1,双num2){
返回值(num1+num2);
}
公共无效计算表(int[][]表){
对于(int i=0;i
}
在这里,2D数组的每个单元格将存储其两个索引的总和。如果
calculate
定义在同一个类中,您可以简单地调用它。请显示calculate
方法