2015-10-28 3 views
1

Я пытаюсь написать класс Student, который должен работать с StudentDriver. Тем не менее, мне очень тяжело обволакивать концепцию методов и классов. Я не знаю, как получать и возвращать данные. Более того, я даже не знаю, правильно ли объявляю свои данные. Пожалуйста, помогите мне. Буду весьма признателен за это.Создание методов и классов (Java)

Также, когда я скомпилировал Студента, он говорит, что он не может найти символ this.setGPA. Как так? Когда в драйвере есть .setGPA.

спасибо.

// This will be the "driver" class for the Student class created in 
// MinilabWritingClasses (It looks very complicated because of all 
// the comments, but it really just creates instances of Student and 
// tells them to do things...) 

public class StudentDriver 
{ 
public static void main(String[ ] args) 
{ 
    //create an instance of Student 
    System.out.println("***** Creating a Student, calling the default constructor"); 
    Student stud1 = new Student(); 

    //print it so we can see what the default values were for the class data 
    //note that its toString() will be called automatically 
    System.out.println("\n***** printing it - notice the default values (set by Java)"); 
    System.out.println(stud1); 

    //create another instance of a Student, passing in initial values to its constructor 
    System.out.println("\n***** Creating another Student, passing initial values to its constructor"); 
    Student msBoss = new Student("Bill Gates", 56, 'm', 3.2, true); 

    //tell it to return its age 
    System.out.println("\n***** telling it to return its age."); 
    int theAge = msBoss.getAge(); 
    System.out.println("Its age is: " + theAge); 

    //print it - note that its toString() will be called automatically; 
    System.out.println("\n***** printing it - see if values are correct"); 
    System.out.println(msBoss); 

    //ask it if it is on probation 
    System.out.println("\n***** asking it if it is on probation (check answer)"); 
    System.out.println("onProbation() returned: " + msBoss.onProbation()); 

    //tell it to change its gpa to 1.3 
    System.out.println("\n***** telling it to change its gpa to 1.3"); 
    msBoss.setGPA(1.3); 

    //print it now 
    System.out.println("\n***** printing it - see if the values are correct"); 
    System.out.println(msBoss); 

    //ask it if it is on probation now 
    System.out.println("\n***** asking it if it is on probation (check answer)"); 
    boolean boolAnswer = msBoss.onProbation(); 
    System.out.println("onProbation() returned: " + boolAnswer); 

    //tell it to complain 
    System.out.println("\n***** telling it to complain"); 
    System.out.println("complain() returned: " + msBoss.complain()); 

    //tell it to change its onScholarship field to false 
    System.out.println("\n***** telling it to change its onScholarship field to false"); 
    msBoss.setOnScholarship(false); 

    //print it now 
    System.out.println("\n***** printing it - see if the values are correct"); 
    System.out.println(msBoss); 

    //ask it if it is on probation now 
    System.out.println("\n***** asking it if it is on probation (check answer)"); 
    boolAnswer = msBoss.onProbation(); 
    System.out.println("onProbation() returned: " + boolAnswer); 

    //create a different student, tell it to have some different values, and tell it to print itself 
    System.out.println("\n***** creating a different Student, passing initial values to its constructor"); 
    Student stud2; 
    stud2 = new Student("Hillary Clinton", 64, 'f', 2.0, true);   //notice-can define variable and create it in 2 steps 

    //print it 
    System.out.println("\n***** printing it - see if the values are correct"); 
    System.out.println(stud2); 

    //ask it if it is on probation now 
    System.out.println("\n***** asking it if it is on probation (check answer)"); 
    boolAnswer = stud2.onProbation(); 
    System.out.println("onProbation() returned: " + boolAnswer); 
} 
} 

Вот класс, который я пишу.

public class Student 
{ 
private String name; 
private int age; 
private char gender; 
private double gpa; 
private boolean onScholarship; 

public Student() 
{ 
} 

public Student(String newName, int newAge, char newGender, double newGPA, boolean newScholarship) 
{ 
    this.name = newName; 
    this.age = newAge; 
    this.gender = newGender; 
    this.gpa = newGPA; 
    this.onScholarship = newScholarship; 
} 

public int getAge(int newAge) 
{ 
    return age; 
} 

public double setGPA (double newGPA) 
{ 
    this.setGPA = newGPA; 
} 

public boolean setOnScholarship (boolean newScholarship) 
{ 
    this.setOnScholarship = newScholarship; 
} 

public String toString() 
{ 
    return this.name + "\t" + this.age + "\t" + this.gender + "\t" + this.setGPA + "\t" + this.setOnScholarship; 
} 

public boolean onProbation() 
{ 
    if (onScholarship==true && gpa < 2.0) 
     return true; 
    else 
     return false; 
    } 

} 
+1

Что такое '' определенные данные'? Можете быть более конкретными? – sam

+0

В значительной степени я имею в виду все из них, boolean, int, string, double, char и т. Д. – Paincakes

+0

Это должно быть 'this.gpa'. Кроме того, поскольку вы не возвращаетесь из 'setter', сделайте его' void' – sam

ответ

2

Попробуйте изменить эту строку:

this.setGPA = newGPA; 

к этому:

this.gpa = newGPA; 

setGPA символ не найден, потому что нет setGPAполе (это метод). Вы пытаетесь изменить поле gpa.

Вам также не нужен пустой конструктор public Student() {} - это автоматически создается Java.

Кроме того, поскольку @Sam указал, поскольку setOnScholarship() ничего не возвращает, вы можете изменить тип возврата boolean на номер void. Это связано с тем, что нет инструкции return, и это return ничто не является типом void.

В целом у вас есть хорошее понимание создания экземпляров другого класса (т. Е. Создания Student).


По требованию (хотя он не имеет много общего с вашим кодом), вот краткое резюме на static.

Ключевое слово static используется с методами и полями, которые не используются с экземпляром этого класса, но самим классом.

Например, в вашем случае, в значительной степени все Student поля и методы не являются статическими, потому что они являются свойствами Student объектов:

this.gpa; 
this.setGpa(); 

С другой стороны, если не меняется переменная связана с одного объекта, например, общее количество студентов, можно создать статическое поле в Student:

public class Student { 

    // non-static fields for each instance 
    public double gpa; 

    // static field for the class 
    public static numStudents; 

    public Student() { 
     // create student by setting object (non-static) fields, for example... 
     this.gpa = 3.2; 

     // edit static variable 
     numStudents++; // notice how there is no `this` keyword - this changes a static variable 
    } 

} 

... и от StudentDriver, numStudents можно получить с помощью:

Student.numStudents; // notice how this is like `this.[property]`, but with the class name (Student) - it is an instance of the class 

Надеюсь, это поможет! Программирование ООП - сложная тема, которую невозможно объяснить так просто.

+0

Спасибо. Начинаем получать его сейчас. – Paincakes

+0

@sam Где это? –

+0

@Paincakes Я рад, что помог (не забудьте принять)! –