0

你好 stackoverflow 社区。目前我是java新手,我正在尝试弄清楚如何模块化程序。无论出于何种原因,当我返回变量 averageScore 时,它​​都会在 main 方法中给我该变量的错误。任何帮助,将不胜感激。

public class Program4
{

public static void main(String[  ] args)
{
    EasyReader console = new EasyReader(); //Connect to EasyReader.class
    System.out.print("Enter the score from game 1: ");
    double score1 = console.readDouble(); //Reads the user input for game 1 
    System.out.print("Enter the score from game 2: ");
    double score2 = console.readDouble(); //Reads the user input for game 2
    System.out.print("Enter the score from game 3: ");
    double score3 = console.readDouble(); //Reads the user input for game 3
    average(score1, score2, score3);
    displayScores(score1, score2, score3, averageScore);
}
public static void average(double score1, double score2, double score3)
{
    double averageScore = ((double)score1+score2+score3)/3; //Divides miles by gallons  
    getAverage();
}
public static double getAverage()
{
    return new averageScore;
}   
public static void displayScores(double score1, double score2, double score3, double averageScore)
{
    System.out.println("Game 1 Score: " + score1 + " points"); //Prints score 1
    System.out.println("Game 2 Score: " + score2 + " points"); //Prints score 2
    System.out.println("Game 3 Score: " + score3 + " points"); //Prints score 3     
    System.out.println("Average score: " + RoundDouble.roundDouble(averageScore, 2) + " points "); //Prints the average score and rounds it to 2 decimals
}
}
4

3 回答 3

0

尝试这个:

public static double average(double score1, double score2, double score3)
{
    return ((double)score1+score2+score3)/3; //Divides miles by gallons  
}

然后在您的主要方法中,您可以执行以下操作:

EasyReader console = new EasyReader(); //Connect to EasyReader.class
System.out.print("Enter the score from game 1: ");
double score1 = console.readDouble(); //Reads the user input for game 1 
System.out.print("Enter the score from game 2: ");
double score2 = console.readDouble(); //Reads the user input for game 2
System.out.print("Enter the score from game 3: ");
double score3 = console.readDouble(); //Reads the user input for game 3
double averageScore = average(score1, score2, score3);
displayScores(score1, score2, score3, averageScore);

您不再需要 getAverage() 方法

于 2013-09-17T13:32:28.827 回答
0

您的变量score1, score2, score3,averageScores都是方法内部的局部变量。将它们声明为attributesclass Program4然后通过instantiating的对象访问它们Class Program4

于 2013-09-17T13:32:35.103 回答
0

这里有几个问题:

average(score1, score2, score3);

您尚未将返回值分配给本地可访问的任何内容。例如,将 的值分配average()给局部变量,就像您对 score3 所做的那样。

public static void average(double score1, double score2, double score3)
{
    double averageScore = ((double)score1+score2+score3)/3; //Divides miles by gallons  
    getAverage();
}

什么?只需averageScore从这里返回,无需调用其他方法即可。

于 2013-09-17T13:34:39.193 回答