I am trying to write a class called Student that is supposed to work with a StudentDriver. However, I am having a very hard time wrapping my head around the concept of methods and classes. I do not know how to receive and return data. Moreover, I don't even know if I am declaring my data correctly. Please help me. I would greatly appreciate it.
Also when I compiled the Student it says that it cannot find the symbol this.setGPA. How so? When in the driver it has .setGPA.
Thank you.
// 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);
}
}
Here is the class that I am writing.
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;
}
}
Try to change this line:
this.setGPA = newGPA;
to this:
this.gpa = newGPA;
setGPA symbol not found is because there is no setGPA field (it is a method). You are trying to change the gpa field.
You also don't need the empty public Student() {} constructor -- this is automatically created by Java.
Also, as #Sam pointed out, since setOnScholarship() doesn't return anything, you can change the return type boolean to void. This is because there is no return statement, and this returning of nothing is a void type.
Overall, though, you have a good understanding on creating instances of another class (i.e., creating Students).
On request (although it doesn't have much to do with your code), here is a brief summary on static.
The static keyword is used with methods and fields that are not used with an instance of that class, but the class itself.
For example, in your case, pretty much all of the Student fields and methods are non-static, because they are properties of Student objects:
this.gpa;
this.setGpa();
On the other hand, if it were not changing a variable related to a single object, for example the total number of students, you could create a static field in 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
}
}
... and from StudentDriver, numStudents can be retreived with:
Student.numStudents; // notice how this is like `this.[property]`, but with the class name (Student) - it is an instance of the class
I hope this helps! OOP programming is a difficult topic that can't be explained so simply.
Related
The code doesn't show any errors. However, I am getting an unexpected output. I am supposed to get the smallest number for age, but what I keep getting is the last value entered for age. Can you help me point out the mistakes in this code?
Maybe there is some logical error in the getYoungestPet() method?
package pet;
public class Pet
{
public static String petName;
public static int petAge, petWeight;
int youngestAge=9999;
static int test;
public static String setPetName()
{
return petName;
}
public int setPetAge()
{
return petAge;
}
public int setPetWeight()
{
return petWeight;
}
public int getYoungestPet() //probably an error here..?
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}
}
package pet;
import java.util.Scanner;
public class PetMain extends Pet
{
public static void main(String[] args)
{
System.out.println("How many pets do you want to enter? " );
Scanner data= new Scanner(System.in);
int petNumber=data.nextInt();
for (int i = 1;i<=petNumber; i++)
{
Pet PetObject = new Pet();
System.out.println("Please enter name for Pet " + i );
Scanner input = new Scanner(System.in);
petName= input.next();
System.out.println("Your pet's name is : " + petName);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Age" );
petAge= input.nextInt();
System.out.println("Your pet's age is : " + petAge);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Weight" );
petWeight= input.nextInt();
System.out.println("Your pet's weight is : " + petWeight);
System.out.println(" ");
System.out.println(PetObject.getYoungestPet());
}
}
}
The code is supposed to show the smallest age but it shows the latest entered age.
you should declare youngestAge as static variable. so that all of the petObject could share the same value.
static int youngestAge=9999;
your setter and getter methods are also not proper.
public static String setPetName()
{
return petName;
}
should be:
public static void setPetName(String name)
{
petName=name;
}
Also don't forget to set values into PetObject from main method.
...
petName= input.next();
PetObject.setPetName(petName);
...
There are many things that are problematic with this code.
But just to answer your question directly, think about how many pet objects there could be in this program if every time the for loop runs it recreates the pet object because it is inside the for loop.
however, simply moving it outside the for loop will not help because then you will simply keep resetting the values of the same pet object every time you run the for loop.
Consider making an array of pet objects.
Also, your code never actually accesses the pet objects instance variables
In addition, there are other problems with your use of static as others have pointed out.
cheers.
Each time you are creating a Pet, you are getting a different youngestAge with value 9999 for that object. So each time it is comparing the latest petAge with 9999 and giving you the latest petAge as your enterd petAge is less than 9999.
If you need to store the smallest age, then keep it in a static field. Cause, keeping an extra field to store the smallest age for all object is redundant for memory.
If you want your desired output with the existing design, then do this:
Make youngestAge static:
static int youngestAge=9999;
And also don't forget to make the method static too. There is no need to make it object property anymore, both the field variables, it is using, are static.
public static int getYoungestPet()
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}
I have this method addPerson (on the main) which is used to set the name of a person.
private static Person[] addPerson(Person _person[], int _minAge, int _id){
int personAge;
String personName;
Scanner scan = new Scanner(System.in);
System.out.println("What's his age?");
personAge = scan.nextInt();
if(personAge >= _minAge){
if(!_person[_id].getPerson().equals("")){
System.out.println("Person " + _person[_id].getPerson() + " already exists.");
}else{
System.out.println("Enter the name of the person");
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
_person[_id].setPerson(personName);
}
}else{
System.out.println("Person is not old enough");
}
return _person;
}
And here is the method setPerson in my custom class which is used to set the name of the person.
public void setPerson(String name){
System.out.println("Person added");
personName = name;
}
I know I should be doing the checking on whether that person already exists inside my setPerson method, but I am sort of confused with this. As you see I am expecting the user to input an integer, so I guess that I should check that right away to not get an error in case he inputs a string.
So my question is which should be checked within the same method and which on the method on my custom class?
Your code (and your question) is a bit confusing, but from what I can understand you want to know if you should check whether a person exists in the array in setPerson() or not?
Well, from what I can gather from your code, you should not do it in setPerson(), because that's a method in the Person class. The Person class shouldn't need to know anything about your array of Person objects.
So the way you're doing it now is probably your best bet.
Some general hints about the code:
There's no need to create a new Scanner, you can just use the one you have. So this
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
becomes this
personName = scan.next();
I would also suggest you use the name setName()instead of setPerson()for your method name, it doesn't make sense to have it named one way when what it's actually doing is something else.
I would do it this way. However I don't have java currently so I didn't test this snippet.
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}
class Main {
private static final int minAge = 22;
private static Map<Person> addPerson(Map<Person> people, int id) {
if(people.containsKey(id)) {
// print that person with this id exists
return people;
}
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
if(age < minAge) {
// print that given age is invalid
return people;
}
String name = scanner.next();
people.get(id).setName(name);
return people;
}
}
As is, it does compile.
Bug = printing breed and declawed statements on same line. Cannot get rid of this bug for some reason
Bug = unable to get the result logic to compile and print for
console (newb)
There are examples a little like mine posted but they really haven't done anything to help because they are not exactly what I think I'm supposed to be going for. One worked perfect but uses and array and we aren't even to that part yet in my course. Here are the teachers instructions and some tips he gave me and then my code so far. Some of it is commented out since I'm trying to get rid of bugs before printing the result. Also I did change some of the names for convenience until the assignment is complete. Sorry for any formatting issues. Any advice?
In this order:
assignment instruction for class file
tip from the teacher
class file code so far
assignment for the driver file
driver file code so far
ASSIGNMENT INSTRUCTIONS FOR THE CLASS FILE:
Create a new class called Cat that includes the functionality below
The new class has the attributes of:
name – type String
age – type integer
weight – type double
breed - type String
declawed - type boolean - true for has no claws, false for has claws
Be sure your classes have a reasonable complement of constructor, accessor and mutator methods. Every member variable must have at least one independent accessor and one independent mutator.
Example:
public void setName(String name) mutator used to set name
public void setBreed(String breed) mutator used to set the breed
public void set(Boolean declawed) used to set claws or not
****(You must overload the set method to set deClawed value)** what is this?**
public String getName() accessor used to get name
public String getBreed() accessor used to get breed
public boolean getBoolean() access used to get the value of declawed
Ensure you use the “this” reference from within this class when referring to every instance variable or instance method of the current object.
TIP FROM THE TEACHER:
for your IF statement you will only use Age and Claw methods but
then at the end when you print out everything you will need the rest of the
methods. You can create a display method to display all the print
statements for each category such as name, age, etc...then it becomes
easier to display this in the main method - here would be your code in the
main method:
System.out.println("The cat data entered is: \n");
myCat1.display();
myCat2.display();
myCat3.display();
code for class file so far
/*************************************************************************************************
*Cat.java
*Jonathan Nees
*
*Cha. 6 OOP
*************************************************************************************************/
import java.util.Scanner;
public class Cat
{
private String name;
private int age;
private double weight;
private String breed;
private boolean declawed;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return this.age;
}
public void setWeight(double weight)
{
this.weight = weight;
}
public double getWeight()
{
return this.weight;
}
public void setBreed(String breed)
{
this.breed = breed;
}
public String getBreed()
{
return this.breed;
}
public void setDeclawed(boolean declawed)
{
this.declawed = declawed;
}
public boolean isDeclawed()
{
if (!this.declawed == false)
{
return true;
}
else
{
return false;
}
}
Scanner input = new Scanner(System.in);
public void display()
{
System.out.print("Enter the name of Cat: ");
this.name = input.nextLine();
System.out.print("Enter the age of Cat: ");
this.age = input.nextInt();
System.out.print("Enter the weight of Cat: ");
this.weight = input.nextDouble();
System.out.print("Enter the breed of Cat: ");
this.breed = input.nextLine();
System.out.print("Does the cat have claws? True or False?: ");
this.declawed = input.nextBoolean();
}
}
Assignment instructions for the driver file
Write a driver program that reads in 3 pets of type Cat and prints out the name and age of all cats with claws and over 3 years old.
The following information should be read in:
Name (as String)
Age (as int)
Weight (as double)
Breed (as String)
DeClawed (as boolean)
Ensure you use the accessor methods to check the age and claws.
code for driver file so far
/*************************************************************************************************
*CatDriver.java
*Jonathan Nees
*
*Cha. 6 OOP Driver
*************************************************************************************************/
import java.util.Scanner;
public class CatDriver
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Cat Cat1 = new Cat();
Cat Cat2 = new Cat();
Cat Cat3 = new Cat();
Cat1.display();
System.out.println();
Cat2.display();
System.out.println();
Cat3.display();
System.out.println();
//*for (int i=0; i<3; i++)
//{
// System.out.println("The cats over 3 with claws are:");
// if ((!this.age() <= 3) && (this.Declawed() == true))
// {
// System.out.println("Name: " + this.name);
// System.out.println("Age: " + this.age + "Years Old");
// }
//}
}
}
Like I said I've commented some out to work out the bugs before doing the result.
It almost works! Sorta...
I was able to get it to work. I rewrote your display method using setter methods and it did the trick. Also, your declawed setter method is written a little confusingly so you may want to tinker with it.
Try this:
public void display()
{
System.out.print("Enter the name of Cat: ");
this.setName(input.nextLine());
System.out.print("Enter the age of Cat: ");
this.setAge(Integer.valueOf(input.nextLine()));
System.out.print("Enter the weight of Cat: ");
this.setWeight(Double.valueOf(input.nextLine()));
System.out.print("Enter the breed of Cat: ");
this.setBreed(input.nextLine());
System.out.print("Does the cat have claws? True or False?: ");
this.setDeclawed(!Boolean.valueOf(input.nextLine()));
}
I am a java-noob as I recently started to learn in a course.
I have created a class:Humans which have ability to store their name and age, and also a subclass Students which extends Humans and adds the Year they began there studies.
I have constructed a randomHuman constructor where I call it(in my main class) and create a list with the humans(with random name and age).
My problem is when i want to random 5 human non-students and 5 students and create this list, I'm not sure how to find out what type of object is sent to the random constructor, so i know if i should give it a year or not. And what type to tell the constructor to return.
I am sorry that this turned into an essay, but if anyone would be so kind to help then I would greatly appreciate it.
TLDR; How to expand a randomHuman constructor to take two types of objects?
Here is my main class:
public class Main {
public static void main(String []args){
Human newHuman = new Human( 18, "Tommy");
System.out.println("Age: " + newHuman.getAge());
System.out.println("Name: " + newHuman.getName());
System.out.println(newHuman.toString());
Human putte = new Human (25,"Putte");
System.out.println(putte);
//Varför blir det så?
//kanske lokal variabel
//Array RandomHumans
System.out.println(" ");
System.out.println("Array Human");
ArrayList<Human> myAl = new ArrayList();
for(int i = 0; i<15; i++){
Human xx =Human.randomHuman();
myAl.add(xx);
}
//Array RandomFysiker
for(int j = 0; j<myAl.size(); j++){
Human var = myAl.get(j);
System.out.println(var.toString());
}
System.out.println(" ");
System.out.println("Array Fysiker");
ArrayList<Fysiker> myAl2 = new ArrayList();
//puts the Fysiker in an array
for(int i = 0; i<15; i++){
Fysiker xx =Fysiker.randomHuman();
myAl2.add(xx);
}
//prints teh array
for(int j = 0; j<myAl2.size(); j++){
Fysiker var = myAl2.get(j);
System.out.println(var.toString());
}
}
}
and my Human class:
public class Human {
public String name;
public int age;
Human(int ageIn, String nameIn){ //Constructor
age=ageIn;
name=nameIn;
}
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String toString(){
return "Name: " + getName() +"," + " Age: " + getAge();
}
//Random human
// Behöver ändra konstruktorn så att den kan kolla
// om objectet är Fysiker eller Human och sedan,
// Behandla dom olika
//Problem1: Hur kollar man? Föreslag if(obj instanceof Fysiker), men vad ska jag ha som obj
//Problem2: Vilken returtyp ska man då ha?
public static Human randomHuman(){
String[] anArrayOfStrings={"Tom", "Jon", "Chris","Julian","Roberto","Sam","Lisa","Roxanne","Rebecca","Anton","Johannes","Antonella","Bianca"};
int randomAge = (int) (100*Math.random());
String randomName = anArrayOfStrings[(int)(Math.random()*anArrayOfStrings.length)];
int RandomYear = (int) (Math.random()*(2013-1932) + 1932);
// if(xx instanceof Fysiker){
//
// }
return new Human(randomAge,randomName);
}
}
and the subclass Fysiker(aka student):
/**
*
* #author Julian
*/
public class Fysiker extends Human{
public int schoolYear;
public Fysiker(int startYear,int ageIn, String nameIn){
super(ageIn, nameIn);
if (age>15){
if (startYear>2013){
} else if (startYear<1932){
} else {
schoolYear = startYear;
}
} else {
}
}
public int getYear(){
return schoolYear;
}
public String toString(){
return super.toString() +","+" Startyear: " +getYear();
}
}
Actually, your randomHuman() method, as mentioned in the comments, is not a constructor at all. It's a static factory method, although I'm sure you're not aware of what that means as yet.
Basically, a constructor is not a method at all and doesn't have a return type. What a constructor does is provide an initialization for a new instance of the class, created by using new, although it can do things that don't strictly initiate the fields of that object.
A method, in contrast, can return something. And in your particular case, the last line actually tells you exactly what it returns - it's calling new for the class Human, so it will return an object of class Human, never a Student.
In fact, the class Human is not aware of the class Student. In principle, you could write a subclass for a class, years after the parent class has been written. Parent classes don't need to know about their descendents. They just decide what they allow those descendents to change and what they don't allow them to change.
You could, in theory, put a method in Human that creates a Student instance. But I'm pretty sure that's not needed in the current situation.
What you probably want to do is fill a list of humans outside the definition of either Human or Student. Filling a random list is probably not part of "being a human" or "being a student" is all about, so you should just do it in your Main class, calling new Human() or new Student() as you wish and filling them as appropriate. Since you know which new you called, you also know whether or not to use a random year.
You could do it in a static method in your Main class, to signify that this is something you do for testing, and not really part of the logic of either a Human or a Student.
As for being able to tell which object you now got from the list - you can do that with instanceof. But you'll also need to typecast it to Student if you want to access its getYear() method.
However - and this is the neat thing about polymorphism - if you just call the toString() method, and don't even check the type of the object, you'll get it with the year if it's really a Student object, and without it if it's a plain Human object.
Let's assume your teachers actually want you to extend the randomHuman method so that it sometimes gives Human instances, and sometimes Students. When it gives Student, it should of course provide it with a year.
As I said above, this is called Tight Coupling between parent and subclass, and is not recommended. If I wanted to build another human subclass, such as Politician, I'd have to call you and ask you to release a new version of Human that also sometimes gives random Politicians. So, under protest, I'll explain how to do it.
Your existing function is:
public static Human randomHuman(){
String[] anArrayOfStrings={"Tom", "Jon", "Chris","Julian","Roberto","Sam","Lisa","Roxanne","Rebecca","Anton","Johannes","Antonella","Bianca"};
int randomAge = (int) (100*Math.random());
String randomName = anArrayOfStrings[(int)(Math.random()*anArrayOfStrings.length)];
int RandomYear = (int) (Math.random()*(2013-1932) + 1932);
// if(xx instanceof Fysiker){
//
// }
return new Human(randomAge,randomName);
}
We change it like so:
public static Human randomHuman(){
String[] anArrayOfStrings={"Tom", "Jon", "Chris","Julian","Roberto","Sam","Lisa","Roxanne","Rebecca","Anton","Johannes","Antonella","Bianca"};
int randomAge = (int) (100*Math.random());
String randomName = anArrayOfStrings[(int)(Math.random()*anArrayOfStrings.length)];
Human result = null;
if ( Math.random() < 0.5 ) {
// With a probability of 50%, create a plain human
result = new Human( randomAge, randomName );
} else {
// Create a student. Start by calculating a random year.
int randomYear = (int) (Math.random()*(2013-1932) + 1932);
result = new Fysiker( randomYear, randomAge, randomName );
}
return result;
}
So, you decide that you want to make a plain human, and within the scope of that decision, you create it with new Human(...) and assign to the result variable.
If you decide to make a student, within the scope of that decision, you calculate a random year, and create it with new Fysiker(). You can assign it to the variable result because polymorphically, it's Human. But in reality, internally, it's a Student.
You return the result variable, which may contain either a Human or a Student at this point.
For determining what type the object instance is use either object instanceof class or object.getClass().equals(Clazz.getSimpleName())
For return type just use the superClass (or interface). You can always cast it to the child if needed.
If you want to create 5 class of each you need a boolean in the method declaration and call it 5 times each to be sure u will have 5 instances of each class.
public static Human randomHuman(boolean isHuman){
If this is not important u can add a random boolean and then call the constructor:
boolean isHuman = Math.random() < 0.5;
if(!isHuman){
int RandomYear = (int) (Math.random()*(2013-1932) + 1932);
// create student
} else {
// create human
}
Ok, now I think I've given up all hope of finding solution to what should to be a simple problem. Basically, I'm creating a students' record system that stores students' details in an ArrayList. I first created a constructor in the Student class to specify what entries each student will have. I then created an instance of the Student class in the main class (i.e. class with the main method) and then added the student object to the studentList ArrayList.
By the way, instead of hard-coding the student details, my initial aim was to let the user enter the details and then I'll use a Scanner or BufferedReader object to get the details stored in the Student object, and then to the ArrayList but I'm having trouble with that as well; so I'll probably tackle that problem as soon as I'm done with this one.
Anyway, I'm expecting the output to print out the students' details but instead I get a memory location (i.e. [studentrecordsys.Student#15c7850]). I'm aware that I need to override the toString method but how exactly this is done is what I can't seem to get. I get syntax errors everywhere as soon as I enter the #Override code block for the toString method. Here's what I've tried:
import java.util.*;
class Student {
private String studentID;
private String studentName;
private String studentAddress;
private String studentMajor;
private int studentAge;
private double studentGPA;
Student (String studentID, String studentName, String studentAddress, String
studentMajor, int studentAge, double studentGPA){
this.studentID=studentID;
this.studentName=studentName;
this.studentAddress=studentAddress;
this.studentMajor=studentMajor;
this.studentAge=studentAge;
this.studentGPA=studentGPA;
}
}
public static void main(String[] args) {
Student ali = new Student("A0123", "Ali", "13 Bond Street", "BSc Software Engineering", 22, 3.79);
List<Student> studentList = new ArrayList<>();
studentList.add(ali);
#Override
String toString() {
StringBuilder builder = new StringBuilder();
builder.append(ali).append(studentList);
return builder.toString();
}
System.out.println(builder);
}
You need to implement the toString() on the Student object.
public class Student {
...
Your existing code
...
#Override
public String toString() {
return studentID + ", " + studentName + ", " + //The remaining fields
}
}
then in your main method, call
for (Student student : studentList) {
System.out.println(student.toString());
}
You to override toString method because it is going to give you clear information about the object in readable format that you can understand.
The merit about overriding toString:
Help the programmer for logging and debugging of Java program
Since toString is defined in java.lang.Object and does not give valuable information, so it is
good practice to override it for subclasses.
Source and Read more about overriding toString
public String toString() {
return "Studnet ID: " + this.studentID + ", Student Name:"
+ this.studentName+ ", Studnet Address: " + this.studentAddress
+ "Major" + this.studentMajor + "Age" + this.studentAge
+ GPA" + this.studentGPA ;
}
You get errors because you have to Override the toString method inside the class you want to use it for. i.e you have to put the method, with the #Override inside your Student class.
And you can call it like this:
System.out.println(studentA.toString());
System.out.println(studentB.toString());
or in a loop:
for(Student x : studentList)
System.out.println(x.toString());
and so on..
Also, in your code you create a method inside your main method. Of course you will get errors.