Java新手在这里,我有一个任务,我需要编写一个类来创建学生对象,然后还写一个驱动程序。
我完成了所有要求,除了我遇到这个问题 - “写方法getTestScore接受测试编号并返回适当的分数。”
我相信我已经正确地编写了类,但是我在编写驱动程序代码时遇到了麻烦。
在提示用户输入测试编号后,它没有返回任何内容,程序终止返回适当的分数。
非常感谢帮助!
这是班级:
public class Student
{
private String firstName, lastName;
private String homeAddress, schoolAddress;
private int testScore1, testScore2, testScore3;
//Constructors
public Student()
{
firstName = "None";
lastName = "None";
homeAddress = "None";
schoolAddress = "None";
testScore1 = 0;
testScore2 = 0;
testScore3 = 0;
}
public Student(String first, String last, String home, String school, int score1, int score2, int score3)
{
firstName = first;
lastName = last;
homeAddress = home;
schoolAddress = school;
testScore1 = score1;
testScore2 = score2;
testScore3 = score3;
}
//Setter for test scores
public void setTestScore(int testNum, int score)
{
if (testNum == 1)
testScore1 = score;
else
if (testNum == 2)
testScore2 = score;
else
if (testNum == 3)
testScore3 = score;
else
throw new IllegalArgumentException(testNum + " is out of range");
}
//Getter for test scores
public int getTestScore(int testNum2)
{
if (testNum2 == 1)
return testScore1;
else
if (testNum2 == 2)
return testScore2;
else
if (testNum2 == 3)
return testScore3;
else
throw new IllegalArgumentException(testNum2 + " is out of range");
}
//Calculates average for each student
public int getAverage()
{
int average = (testScore1 + testScore2 + testScore3)/3;
return average;
}
//Returns a description of this Student object
public String toString()
{
String result;
result = firstName + " " + lastName + "\n";
result += "Home Address:\n" + homeAddress + "\n";
result += "School Address:\n" + schoolAddress + "\n";
result += "Test Score 1:\n" + testScore1 + "\n";
result += "Test Score 2:\n" + testScore2 + "\n";
result += "Test Score 3:\n" + testScore3 + "\n";
result += "Average Test Score:\n" + ((testScore1+testScore2+testScore3)/3);
return result;
}
}
这是司机:
package lab7;
import java.util.Scanner;
public class StudentBody {
public static void main(String[] args)
//Create student objects
{
Student snm24 = new Student("Sarah", "M", "18 79th Street", "5000 Forbes Ave.", 95, 80, 63);
Student adk28 = new Student("Andrew", "K", "16 Collins Ave.", "16401 NW 37th Ave.", 90, 82, 76);
//Get average for snm24
snm24.getAverage();
System.out.println("snm24 average initial: " + snm24.getAverage());
//Set new test score for test 3 for snm24 and see new average
snm24.setTestScore(3, 68);
System.out.println("snm24 average after adjustment: " +snm24.getAverage());
//Get test score for adk28
Scanner scan = new Scanner(System.in);
System.out.println("Which test score are you looking for?:");
int testNum2 = scan.nextInt();
adk28.getTestScore(testNum2);
}
}
答案 0 :(得分:1)
它没有返回任何内容,程序终止。非常感谢帮助!
这里>
adk28.getTestScore(testNum2);
返回的值会丢失..用它做一些事情,打印它,将它分配给变量:
int result = adk28.getTestScore(testNum2);