我正在尝试在java中编写一个程序,该程序需要3个学生的姓名和分数,然后计算他们的分数的平均值。以下是我想要实现的详细清单:
import javax.swing.JOptionPane;
public class StudentTester {
public static void main(String args[]) {
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
String firstName;
String lastName;
//start first student here
firstName = JOptionPane.showInputDialog("Enter the student's first name.");
student1.setFirstName(firstName);
lastName = JOptionPane.showInputDialog("Enter the student's last name.");
student1.setLastName(lastName);
JOptionPane.showMessageDialog(null, "Student 1 has name "
+ student1.getFirstName() + ""+ student1.getLastName() + ".");
score1 = JOptionPane.showInputDialog("Enter the student's score.");
student1.setScore(score1);
int student1; getScore();
//start second student here
firstName = JOptionPane.showInputDialog("Enter the student's first name.");
student2.setFirstName(firstName);
lastName = JOptionPane.showInputDialog("Enter the student's last name.");
student2.setLastName(lastName);
JOptionPane.showMessageDialog(null, "Student 2 has name "
+ student2.getFirstName() + "" + student2.getLastName() + ".");
score2 = JOptionPane.showInputDialog("Enter the student's score. ");
student2.setScore(score2);
//start third student here
firstName = JOptionPane.showInputDialog("Enter the student's first name.");
student3.setFirstName(firstName);
lastName = JOptionPane.showInputDialog("Enter the student's last name.");
student3.setLastName(lastName);
JOptionPane.showMessageDialog(null, "Student3 has name "
+ student3.getFirstName() + "" + student1.getLastName() + ".");
//average score
}
}
public class Student {
private String firstName;
private String lastName;
public int score1;
public int score2;
public int score3;
public void setFirstName(String name){
firstName = name;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String name){
lastName = name;
}
public String getLastName(){
return lastName;
}
public String setScore(){
int score1 = Integer.parseInt(score1Store);
}
//method for average score computation
public void score1 = Integer.parseInt(Score);
public double getAverageScore(){
return double = ( score1 + score2 + score3)/3.0;
}
}
我做错了什么?我完全迷失了,并且不确定如何设置整个分数输入和计算。
感谢。
答案 0 :(得分:0)
在学生中,你应该将score1,score2和score3作为私有实例变量放在顶部,并为他们设置getter和setter,就像你对firstName和lastName所做的那样。你可以为每个人设置单独的getter和setter,但有多种方法可以做到这一点。
您可以从getAverageScore返回一个int值,如:
public int getAverageScore() {
float ans = (score1 + score2 + score3)/3.0f;
return Math.round(ans);
我使用了一个浮点数,因为带有double的Math.round将返回一个long。
在main方法中,您可以使用setScores()方法设置分数。
student1.setScore1(score1);
student1.setScore2(score2);
student1.setScore3(score3);
要打印学生,您可以在学生中创建一个toString方法,或者使用您的getter打印它们。 toString方法如下所示:
public String toString() {
return firstName + " " + lastName + " " + score1 + " " + score2 + " " + score3;
}