多个返回??/
问题描述:
只有使用三种方法(包括主)和10个整数数组,我需要建立一个程序,做这些东西:多个返回??/
- 指望有多少人谁通过考试。
- 打印统计信息。 (例如A,B,C,D,E等级)
- 有多少人通过或未通过考试。
这就是我现在所拥有的。我唯一的问题是,我不知道如何返回多个值。
public class Array10PassFail
public static int countPass (int [] num)
{
int count = 0;
int counter = 0;
for (int i = 0; i < num.length; i++)
{
if (num [i] >= 50)
{
count++;
}
else if (num [i] < 50)
{
counter++;
}
}
return count;
}
public static int printStats (int [] num)
{
int aTotal = 0, bTotal = 0,cTotal = 0, dTotal = 0, eTotal = 0;
for (int i = 0; i < num.length; i++)
{
if (num[i] >= 80)
{
aTotal++;
}
else if (num[i] >= 70)
{
bTotal++;
}
else if (num[i] >= 60)
{
cTotal++;
}
else if (num[i] >= 50)
{
dTotal++;
}
else if (num[i] < 50)
{
eTotal++;
}
}
return aTotal;
}
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
int [] num = new int [10];
for (int i = 0; i < num.length; i++)
{
System.out.print("Enter score: ");
num[i] = sc.nextInt();
}
int passf = countPass(num);
System.out.println("There are " + passf + " people who passed and " + ??? + " who failed. ");
}
答
创建一个数组。例如,
public static int[] countPass(int[] num){
int count = 0, counter=0;
for (int i = 0; i < num.length; i++){
if (num [i] >= 50) count++;
else counter++;
}
return new int[]{count,counter};
}
和做这样的事情
int array[] = countPass(num);
System.out.println("Failed -> " + array[1] + "Passed->" + array[0]);
同样,做它的档次。
+0
谢谢!它现在有效 –
答
如果要返回多个值,通常需要返回封装值的单个对象。 使用List>或ArrayList,将您的值添加到列表中并将其返回。在调用函数中,获取列表中的返回值,并按照您认为合适的方式提取信息。
FYI'java'!='javascript' –
将值存储到'Array'中,并将两种方法的返回类型更改为'Array'。 –
您可以创建一个类,称为“结果”,其成员代表您希望从方法返回的多个计算值。然后,在你的方法中,你实例化Result,填充其中的计数,并从你的方法中返回 –