gpt4 book ai didi

java - 编写方法来测试java中的平均成绩

转载 作者:行者123 更新时间:2023-11-30 08:02:38 26 4
gpt4 key购买 nike

我正在为家庭作业编写代码,但遇到了困难。

作业是编写一个程序来获取用户输入的 10 个成绩的平均值。

我相信我得到了大部分,但是在 averageGrades 方法中,当我尝试声明 average 时,它不会让我这样做。

这是我的:

public class Averagegrades 
{
public int min, max;
double average;

public static void main (String [] args)
{

double sum = 0;
Scanner scan = new Scanner(System.in);
int [] gradesarray = new int[10];

System.out.println("Please enter the 10 test grades: ");

for (int i = 0; i < gradesarray.length; i++)
{
gradesarray[i] = scan.nextInt();

if(gradesarray[i] > 100)
{
System.out.println("Please enter a number within 0 - 100: ");
gradesarray[i] = scan.nextInt();
}
}

System.out.println("These are the grades you entered: " +
Arrays.toString(gradesarray));
System.out.println("You have entered " + gradesarray.length + " grades");

for(double num : gradesarray)
{
sum = sum + num;
}

System.out.println("This is the sum " + sum);
}

public double averageGrades()
{
average = sum / (double) gradesarray.length;
}

最佳答案

所以这会让你声明平均。问题是方法 averageGrades 找不到 sum 或 gradesarray,因为这两个变量是在 main 方法中声明的,因此对方法不可见。

package test;

import java.util.Arrays;
import java.util.Scanner;

public class Averagegrades
{
public int min, max;
double average;
static double sum;
static int[] gradesarray;

public static void main (String [] args)
{
sum = 0;
Scanner scan = new Scanner(System.in);
gradesarray = new int[10];
System.out.println("Please enter the 10 test grades: ");

for (int i = 0; i < gradesarray.length; i++)
{
gradesarray[i] = scan.nextInt();
if(gradesarray[i] > 100)
{
System.out.println("Please enter a number within 0 - 100: ");
gradesarray[i] = scan.nextInt();
}
}
System.out.println("These are the grades you entered: "+
Arrays.toString(gradesarray));
System.out.println("You have entered "+gradesarray.length+" grades");

for(double num : gradesarray)
{
sum = sum + num;
}
System.out.println("This is the sum "+sum);
}

public double averageGrades()
{
average = sum / (double) gradesarray.length;
return average ;
}

或者你也可以做...

public double averageGrades(int sum, int[] gradesarray)
{
average = sum / (double) gradesarray.length;
return average ;
}

然后在调用方法时...

averageGrades(sum, gradesarray);

通过这样做,您不必将 sum 和 gradesarray 声明移到 main 方法之外。

希望这对您有所帮助!

关于java - 编写方法来测试java中的平均成绩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36758054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com