Création de Méthodes et de classes (Java)


J'essaie d'écrire une classe appelée Student qui est censée fonctionner avec un StudentDriver. Cependant, j'ai beaucoup de mal à comprendre le concept de méthodes et de classes. Je ne sais pas comment recevoir et retourner les données. De plus, je ne sais même pas si je déclare mes données correctement. S'il vous plaît aider moi. Je vous en serais très reconnaissante.

Aussi quand j'ai compilé l'étudiant, il dit qu'il ne peut pas trouver le symbole ceci.setGPA. Comment alors? Quand dans le conducteur il a .setGPA.

Merci.

// 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);
 }
}

Voici la classe que j'écris.

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;
  }

}
Author: Paincakes, 2015-10-29

1 answers

Essayez de changer cette ligne:

this.setGPA = newGPA;

À ceci:

this.gpa = newGPA;

setGPA symbole pas trouvé car il n'y a pas de setGPA le champ (c'est une méthode). Vous essayez de changer le champ gpa.

Vous n'avez pas non plus besoin du constructeur vide public Student() {} - ceci est automatiquement créé par Java.

De plus, comme @Sam l'a souligné, puisque setOnScholarship() ne renvoie rien, vous pouvez changer le type de retour boolean en void. C'est parce qu'il n'y a pas d'instruction return, et ceci returning de rien est un void type.

Dans l'ensemble, cependant, vous avez une bonne compréhension de la création d'instances d'une autre classe (c'est-à-dire, la création de Student s).


Sur demande (bien que cela n'ait pas grand-chose à voir avec votre code), voici un bref résumé sur static.

Le mot-clé static est utilisé avec des méthodes et des champs qui ne sont pas utilisés avec une instance de cette classe, mais la classe elle-même.

Par exemple, dans votre cas, à peu près tous les Student champs et les méthodes sont non statiques, car ce sont des propriétés des objets Student:

this.gpa;
this.setGpa();

En revanche, s'il ne modifiait pas une variable liée à un seul objet, par exemple le nombre total d'étudiants, vous pourriez créer un champ statique dans 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
    }

}

... et de StudentDriver, numStudents peut être récupéré avec:

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

J'espère que cela aide! La programmation de POO est un sujet difficile qui ne peut pas être expliqué si simplement.

 2
Author: Jonathan Lam, 2015-10-29 00:02:35