【发布时间】:2014-04-08 04:42:17
【问题描述】:
我有 2 节课。 1 个班级设置并获取学生姓名、一个学生的 3 个测试分数和 3 个分数的平均值。另一个类有一个主要的方法来设置和获取这些信息。我的 IDE 仅针对第二类出现错误。
public class Student5th
{ /**
Instance variables
Each student object will have a name and three test scores
*/
private String name; //Student name
private int test1; //Score on test 1
private int test2; //Score on test 2
private int test3; //Score on test 3
/**
Set a student's name
Preconditions -- nm is not empty
Postconditions -- name has been set to name
*/
public void setName (String nm)
{
name = nm;
}
/** Get a student's name
Preconditions -- none
Postconditions -- returns the name
*/
public String getName ()
{
return name;
}
/** Set the score on the indicated test
Preconditions -- 1 <= i <= 3
-- 0 <= score <= 100
Postconditions -- test i has been set to score
*/
public void setScore (int i, int score)
{
if (i == 1) test1 = score;
else if (i == 2) test2 = score;
else test3 = score;
}
/** Get the score on the indicated test
* Preconditions -- none
* Postconditions -- returns the score on test I
* */
public int getScore (int i)
{
if (i == 1) return test1;
else if (i == 2) return test2;
else return test3;
}
/** Compute and return a student's average
* Preconditions -- none
* Postconditions -- returns the average of the test scores
* */
public int getAverage() {
int average;
average = (int) Math.round((test1 + test2 + test3) / 3.0);
return average;
}
}
我的第二堂课,主要方法...
import java.util.*;
public class TestStudent
{
public static void main (String[] args)
{
Scanner console = new Scanner(System.in);
private Student **student1**;
private Student **student2**;
String s;
int t;
student1 = new Student();
student2 = new Student();
s = console.next();
student1.setName (s);
t = console.nextInt();
student1.setScore (1, t);
student1.setScore (2, console.nextInt());
student1.setScore (3, console.nextInt());
student2.setName (**keyboard**.readLine());
student2.setScore (1, console.nextInt());
student2.setScore (2, console.nextInt());
student2.setScore (3, console.nextInt());
}
}
我已经用粗体(好吧,在周围加上双星号)那些给我错误的部分。我快要让这个程序正常工作了,但我不知道为什么我的 IDE 给我第二堂课的 student1 和 student2 带来问题,以及给我一个问题 (keyboard.readLine());为第二班的 student2.setName?
【问题讨论】:
-
看不到粗体部分。你能分享你得到的编译错误吗?
-
你遇到什么错误可以粘贴到这里吗?
-
在 Christian 的回答之上,将你的 student2 行更改为: student2.setName(console.nextLine());
-
对于相同的方法使用修饰符是什么意思?只是从主要方法中删除私有修饰符我的意思是您正在使用学生对象的对象。