Hello 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
}
}
答案 0 :(得分:0)
试试这个:
public static double average(double score1, double score2, double score3)
{
return ((double)score1+score2+score3)/3; //Divides miles by gallons
}
然后在你的main方法中,你可以这样做:
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()方法
答案 1 :(得分:0)
您的变量score1
,score2
,score3
,averageScores
都是方法内的本地变量。
将它们声明为attributes
的{{1}},然后通过class Program4
instantiating
的对象访问它们。
答案 2 :(得分: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
,无需再调用其他方法。