[英]Returning a specific array element from a method
首先,最好首先看以下问题,以使这个问题更有意义。 如何减少这一系列的if语句?
数组的值int[] counterarray = new int[10];
以下是:
counterarray[0] is 3
counterarray[1] is 3
counterarray[2] is 0
counterarray[3] is 0
counterarray[4] is 1
counterarray[5] is 5
counterarray[6] is 0
counterarray[7] is 0
counterarray[8] is 1
counterarray[9] is 2
这段代码确定数组每个元素的上述值:
counterarray = new int[10];
for (int x = 14; x >= 0; x--) {
if (anArray[x] >= 0 && anArray[x] < 101) {
int idx = Math.min(anArray[x] / 10, 9);
++counterarray[idx];
}
}
不应修改。
我试图从方法返回数组中某些元素的值。
因此,我希望能够在需要的时候以及想要的方式中,仅在代码的给定行中返回数组的给定元素。 我怎么做?
当我编译代码时,在方法public static int[] countarraymethod
,上面指出的行上有错误。
Error: Syntax error, insert ". class" to complete Expression
当我在方括号内放一个数字时,出现此错误:
Error: Type mismatch: cannot convert from int to int[]
顺便说一句,我把// return only counterarray[9]
作为注释的原因是因为我不知道如何制作仅返回数组给定元素的命令。
import java.io.*;
import java.util.*;
public class GradesHistogram {
public static int[] countarraymethod (int[] counterarray, int[] anArray, int counterrepeat) {
counterarray = new int[10];
for (int x = 14; x >= 0; x--) {
if (anArray[x] >= 0 && anArray[x] < 101) {
int idx = Math.min(anArray[x] / 10, 9);
++counterarray[idx];
}
}
for (counterrepeat = 0; counterrepeat < 10; counterrepeat++) {
System.out.println("counterarray[" +counterrepeat+ "] is " +counterarray[counterrepeat]);
}
return counterarray[]; //error is here
}
public static void main(String[] args)throws java.io.IOException {
...
...
int histogrammin = 0;
int histogrammax = 0;
x = readnumber;
for (int histogramrows = 0; histogramrows < 10; histogramrows++) {
histogrammin = histogramrows * 10;
if (histogrammin == 90) {
// return only counterarray[9]
} else {
histogrammax = histogrammin + 9;
// return counterarray[0]
// return counterarray[1]
// return counterarray[2]
...
...
// return counterarray[8]
}
}
...
...
}
}
方法的返回类型为int [],因此您必须返回整数数组。 如果只想返回数组的一个元素,则应将方法的返回类型更改为int并返回如下值:
return array[index];
您当前使用的语法无效,因此编译错误。 返回数组时,您无需在变量名称后放置方括号。
int []数组中的一个特定项目只是一个int。 将返回类型更改为int,然后使用:
return counterarray[index];
另外,有点偏离主题,通常这样命名变量是一个好习惯:
return counterArray[index]; //First letter of every word in Uppercase (Except for the first one)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.