"grade" cannot be resolved to a variable - java

I have this exercise and the question is how can I solve the error "grade" cannot be resolved to a variable, without declare it in the class teacher. I suppose is the only error in my code. It is evident for me WHY then in my output only the grade variable is not assigned, but I don't know HOW to solve it.
public class App {
public static void main(String[] args) throws Exception {
Student studentOne = new Student("FraPedu");
Student studentTwo = new Student("FraIla");
Teacher teacherOne = new Teacher();
teacherOne.teacherName = "Tiziana";
teacherOne.assignGrade(studentOne,10);
teacherOne.assignGrade(studentTwo,10);
studentOne.getStudentDetails();
studentTwo.getStudentDetails();
}
}
public class Student {
public String name;
public int grade;
public Student(String studentName) {
System.out.println("Student object has been created succesfully!");
name = studentName;
}
public void getStudentDetails() {
System.out.println("Student name and grade: " + name + " " + grade);
}
}
public class Teacher {
public String teacherName;
public Teacher() {
System.out.println("Teacher object has been created succesfully!");
}
public void assignGrade(Student alum, int finalGrade) {
grade = finalGrade;
}
}

You need to assign the grade to the Student object you are passing to the assignGrade method.
public class Teacher {
public String teacherName;
public Teacher() {
System.out.println("Teacher object has been created succesfully!");
}
public void assignGrade(Student alum, int finalGrade) {
alum.grade = finalGrade; // << this is the line I changed
}
}

Related

Inheritance and arrays in Java

I have a class look like this:
public class People {
private String Name;
private String Address;
public People(String aName, String aAddress) {
this.Name=aName;
this.Address=aAddress;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
void display() {
System.out.println("Name:\t"+Name);
System.out.println("Address:\t" +Address);
}
}
and another 2:
class Students extends People{
private int MatriculationNumber;
private String CourseName;
public Students (String aName, String aAddress, int matriculationNumber, String courseName){
super(aName,aAddress);
this.MatriculationNumber=matriculationNumber;
this.CourseName=courseName;
}
void display() {
super.display();
System.out.println("Matriculation Number: \t" +MatriculationNumber);
System.out.println("Course Name: \t" +CourseName);
}
}
class Staffs extends People{
private int EmployeeNumber;
private String Department;
public Staffs (String aName, String aAddress, int employeeNumber, String department){
super(aName,aAddress);
this.EmployeeNumber=employeeNumber;
this.Department=department;
}
void display() {
super.display();
System.out.println("Employee Number: \t" +EmployeeNumber);
System.out.println("Department: \t" +Department);
}
}
The question is how to create a class named "School" which have a List can contain both Students and Staffs, so I can add a method like AddPeople() which can add or remove Students or Staffs from it?
You can use the below solution. The solution is not thread-safe but should work fine for your usecase.
import java.util.ArrayList;
class School {
private List<People> peopleList = new ArrayList<People>();
public void addPeople(People people) {
peopleList.add(people);
}
public void removePeople(People people) {
peopleList.remove(people);
}
public static void main(String... args) {
Student student = new Student("Name", "Address", 90, "Course");
Staff staff = new Staff("Name", "Address", 1001, "Department");
School school = new School();
school.addPeople(student);
school.addPeople(staff);
school.removePeople(student);
school.removePeople(staff);
}
}
You can create a new Staff Class which also extends from the People Class
package so;
public class Staff extends People {
public Staff(String aName,String aAddress) {
super(aName, aAddress);
}
}
Then give as type of your list the base class People.
package so;
import java.util.ArrayList;
import java.util.List;
public class School {
List<People> peopleContainer = new ArrayList<People>();
public void addPeople(People p){
this.peopleContainer.add(p);
}
public void removePeople(People p) {
this.peopleContainer.remove(p);
}
public void displayPeople() {
for(People person : peopleContainer) {
person.display();
}
}
}
Then you can add staff and student objects to your list and also all other objects which classes extends from people or even people objects itself.
package so;
public class Main {
public static void main(String[] args) {
Students stud1 = new Students("Max", "MustermanAddress", 181242, "CS50");
Staff staff1 = new Staff("Christian", "AugustAddress");
School school = new School();
school.addPeople(stud1);
school.addPeople(staff1);
school.displayPeople();
school.removePeople(staff1);
System.out.println();
System.out.println();
school.displayPeople();
}
}
Output will be
Name: Max
Address: MustermanAddress
Matriculation Number: 181242
Course Name: CS50
Name: Christian
Address: AugustAddress
Name: Max
Address: MustermanAddress
Matriculation Number: 181242
Course Name: CS50

Why Do i get null value in the following code concerning java inheritence

I will provide the code and the output given by the compiler for better understanding of the problem. You will notice a null value for Registration Number...there is the problem.
You will notice at the output that i get null value for Registration number...i don't get it because it all seemed right, until it wasn't.😒
public class Student {
private String regNo;
//Student student = new Test();
public String getRegNo() {
return regNo;
}
public void setRegNo(String number) {
this.regNo = regNo;
}
public void displayRegistrationNumber(){
System.out.println("Registration number: "+ getRegNo());
}
}
-----------------------------------------------------------------'
public class Test extends Student{
private double sub1, sub2;
public double getSub1() {
return sub1;
}
public void setSub1(double sub1) {
this.sub1 = sub1;
}
public double getSub2() {
return sub2;
}
public void setSub2(double sub2) {
this.sub2 = sub2;
}
public void displayScore(){
System.out.printf("Scores: Subject1 = %.0f, Subject2 = %.0f \n",getSub1(), getSub2());
}
}
-----------------------------------------------------------------------
public class Results extends Test {
private double total;
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public void displayTotalScores(){
setTotal(getSub1()+getSub2());
System.out.printf("Total marks: %.0f \n", getTotal());
}
}
---------------------------------------------------------------------
public class Main_method {
public static void main(String[] args){
Results results = new Results();
results.setRegNo("2017-04-06859");
results.setSub1(75.47);
results.setSub2(89);
results.displayRegistrationNumber();
results.displayScore();
results.displayTotalScores();
}
}
Here's the output. Notice the null
Registration number: null
Scores: Subject1 = 75, Subject2 = 89
Total marks: 164 `
Here instead of assigning parameter number to regNo you just reassigned its own value (which is null initially) to it:
public void setRegNo(String number) {
this.regNo = regNo;
}
so change it to:
this.regNo = number;
This is an expected behavior, the argument you passed to public void setRegNo(String number) is never used.
this.regNo = regNo;
reassigns the the regNo declared in Student class (which in this case is null ) back to the Object which calls it.
change the argument or the assignment statement
i.e
public void setRegNo(String regNo)
or
this.regNo = number;

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade

i have a large scale project in my hands but i simulated the problem i'm struggling with in this example:
my first class:
package asd;
import java.io.Serializable;
public class Grade implements Serializable{
String name;
Integer score;
public String getName() {
return name;
}
public Grade() {}
public Grade(String name, Integer score) {
this.name = name;
this.score = score;
}
public void setName(String name) {
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
my second class:
package asd;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private Object grade;
public String getName() {
return name;
}
public Student(String name, Object grade) {
this.name = name;
Grade = grade;
}
public Student() {}
public void setName(String name) {
this.name = name;
}
public Object getGrade() {
return Grade;
}
public void setGrade(Object grade) {
Grade = grade;
}
}
and this is my main class:
package asd;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
public class Test {
public static void main(String[] args){
Student s1 = new Student();
s1.setName("JeanPierre");
s1.setGrade(new Grade("Math", 8));
Gson gson = new GsonBuilder().create();
String convertedToJson = gson.toJson(s1);
System.out.println("Json string: " + convertedToJson);
Student s2 = gson.fromJson(convertedToJson, Student.class);
System.out.println("Student Name: " + s2.getName());
System.out.println("Grade Name: " + ((Grade)s2.getGrade()).getName());
System.out.println("Grade Score: " + ((Grade)s2.getGrade()).getScore());
}
}
Output:
Json string is :
{"name":"JeanPierre","Grade":{"name":"Math","score":8}}
Student Name: JeanPierre
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade
at asd.Test.main(Test.java:24)
My problem is when i call:
System.out.println("Grade Name: " + ((Grade)s2.getGrade()).getName());
or
System.out.println("Grade Score: " + ((Grade)s2.getGrade()).getScore());
i get this exception:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade
at asd.Test.main(Test.java:24)
Declaration and setting of the Grade in Student is syntactically wrong. Not sure how it's even building like that.
public class Student implements Serializable
{
protected String name ;
protected Grade grade ;
public Student( String name, Grade grade )
{
this.setName(name).setGrade(grade) ;
}
public String getName()
{ return this.name ; }
public Student setName( String name )
{
this.name = name ;
return this ;
}
public Grade getGrade()
{ return this.grade ; }
public Student setGrade( Grade grade )
{
this.grade = grade ;
return this ;
}
}
You need to parse the grade class as well. It won't convert the entire complex object in one attempt. Try the below code:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Test {
public static void main(String[] args){
Student s1 = new Student();
s1.setName("JeanPierre");
s1.setGrade(new Grade("Math", 8));
Gson gson = new GsonBuilder().create();
String convertedToJson = gson.toJson(s1);
System.out.println("Json string: " + convertedToJson);
Student s2 = gson.fromJson(convertedToJson, Student.class);
System.out.println("Student Name: " + s2.getName());
Grade g = gson.fromJson(s2.getGrade().toString(), Grade.class);
System.out.println("Grade Name: " + g.getName());
System.out.println("Grade Score: " + g.getScore());
}
}
Here s2.getGrade().toString() is still a valid JSON string. You are converting that to Grade class and using it. This is the right way to parse complex objects. Hope you understood.
I changed everything to XML and using XStream now, which works on my tests. Thanks for everyone's answers.

Getting NullPointerException errors when trying to use multiple classes for the first time

I am trying to get my addStudent() method in the Roster class to work here.
It's supposed to add a given student to this roster. If the student is already on the roster, or the numStudents == stopPoint, it doesn't change the roster and returns false. If it is successful it returns true.
Roster Class:
public class Roster {
Student[] students;
int numStudents;
int stopPoint;
Course course;
//constructor for this class initialize this roster to empty
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
}
//returns a string that represents the object for printing
public String toString()
{
String res = "";
for(int j = 0; j < numStudents; j++)
{
res = res + "\n" + students[j].toString();
}
return course + " " + numStudents + "/" + stopPoint+res;
}
//returns true if and only if the number of students in it is at stopPoint
public boolean isFull(int numStudents, int stopPoint)
{
if (numStudents == stopPoint)
{
return true;
}
else
return false;
}
/*add given student to this roster if student already on roster
or numStudents already == stopPoint, will not change roster and return
false but return true if successful, else false
*/
public boolean addStudent(Student student)
{
if(this.numStudents < this.stopPoint)
{
this.students[numStudents] = student; // here is where I get the error
this.numStudents++;
return true;
}
else
return false;
}
}
Testing Class:
public class TestRoster
{
public static void main(String[] args)
{
Student s1 = new Student("John","Doe");
Course c1 = new Course(198, 111);
Roster r1 = new Roster(4, c1);
System.out.println(r1);
testAdd(r1, s1);
}
private static void testAdd(Roster r, Student s)
{
System.out.println(s.familyName+" "+r.addStudent(s));
System.out.println(r);
}
}
Student Class:
public class Student
{
String personalName;
String familyName;
public Student(String pName, String fName)
{
personalName = pName;
familyName = fName;
}
public String toString( )
{
return "Student: " + familyName + ", "+ personalName;
}
}
Lastly, the Course Class:
public class Course
{
int deptNum;
int courseNum;
public Course(int deptNum, int courseNum)
{
this.deptNum = deptNum;
this.courseNum = courseNum;
}
public String toString( )
{
return deptNum + ":" + courseNum;
}
}
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at assign4.Roster.addStudent(Roster.java:56)
at assign4.TestRoster.testAdd(TestRoster.java:17)
at assign4.TestRoster.main(TestRoster.java:13)
Java Result: 1`
The other answers suggest using an arbitrary number for the array instansiation, this is not a good idea as you never know if it will be enough.
Your Roster class knows how many students there should be (via the constructor), you should initialize the Student array with stopPoint:
Student[] students;
int numStudents;
int stopPoint;
Course course;
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
this.students = new Student[this.stopPoint]
}
Since you can't touch your class variables, you can and should initialize the array within the constructor.

i have trouble with printing an array after reading it in JAVA

i have problem with printing the array after reading it. After printing, the address of memory is printed, not value of the array. What can i do for that ?
public class MyClass
{
Student St = new Student();
Student[]Array1 = new Student[10];
void AddList()
{
Scanner Scan = new Scanner(System.in);
for (int i=0; i<Array1.length & i<ArrayF1.length; i++)
{
System.out.println("Enter Student NAME Number " + (i+1) + ":");
Array1[i] = new Student();
Array1[i].setName(Scan.next());
//System.out.println("Enter Student MARK Number " + (i+1) + ":");
//St.setMark(Scan.nextFloat());
}
}
this is my print method. The result of print is like this
(studentproject.Student#1a758cb)
void PrintList()
{
for (int i=0; i<Array1.length; i++)
{
System.out.println(Array1[i]);
}
}
this is my Student Class that i have all my setter and getter method on that ... So i have 3 Class how can i work with this 3 class and in one of them get the data and in another print the Mark data and in third class print the Student Name data ... how can i do that ... i do some code but i dont know is it correct or not ... thanks for your help ...
public class Student
{
private String Name;
private float Mark;
/**
* #return the Name
*/
public String getName() {
return Name;
}
/**
* #param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* #return the Mark
*/
public float getMark() {
return Mark;
}
/**
* #param Mark the Mark to set
*/
public void setMark(float Mark) {
this.Mark = Mark;
}
}
Just override the toString() method in Student class, and return the appropriate string you want to get printed when you print an instance.
It may look like: -
#Override
public String toString() {
return "Name: " + studentName;
}
Currently, the default implementation of toString() method of Object class is invoked, and what you are seeing is the format returned from that method, which is of the form - Type#hashCode
Here I've added some stuff how toString() method can be override
public class Student {
private String name;
private int id;
float mark;
public Student() {
}
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMark() {
return mark;
}
public void setMark(float mark) {
this.mark = mark;
}
#Override
public String toString() {
return "Student[ID:" + id + ",Name:" + name + ",Mark:"+mark+"]";
}
public void printStudentInfo() {
// print all the details of student
}
public static void main(String[] args) {
Student[] students = new Student[10];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < students.length; i++) {
System.out.println("Enter Student Name " + (i + 1) + ":");
String name = scanner.nextLine();
Student student = new Student(name, i + 1);
System.out.println("Enter Student MARK Number " + (i + 1) + ":");
float mark = scanner.nextFloat();
student.setMark(mark);
students[i]=student;
}
for(Student student:students) {
// by default toStirng method is called
System.out.println(student);
//or you can call like
//student.printStudentInfo();
}
}
}

Categories