Home > Enterprise >  How do i do math with object instance variables once i have created the object in java
How do i do math with object instance variables once i have created the object in java

Time:05-17

I have constructed an object in java with integer instance variables, how do find the quotient of two of these variables after i have created the object.

The objects i have created are like this:

class Student(int score, int marks)

where score is the score he received in the test and marks is the max score in the test, how can i find the percentage he got, after i have created multiple students like:

Student student1 = new Student(60, 90);

where i want the program to print:

"student1 got " ((score/marks)*100) "%"

Thanks guys!

CodePudding user response:

Here's what I'd recommend:

class Student {

    private int grade; 
    private int maxGrade;

    public Student(int grade, int maxGrade) {
        this.grade = grade;
        this.maxGrade = maxGrade;
    }

    public double getPercentage() {
        return 100.0 * grade/maxGrade;
    }
}
  •  Tags:  
  • java
  • Related