Home > other >  How to set condition for object's property in class java
How to set condition for object's property in class java

Time:07-12

I have a program to enter the student's name, gender, grade, and rank Here is my code:

public class Exercise_W28 { String name; String Sex; int Score; String ratting;

public Exercise_W28(String name, String Sex,
               int Score, String ratting)
{
    this.name = name;
    this.Sex = Sex;
    this.Score = Score;
    this.ratting = ratting;
}

public String getName()
{
    return name;
}

public String getSex()
{
    return Sex;
}

public int getScore()
{
    return Score;
    
}

public String getratting()
{
  
    return ratting;
}

public String toString()
{
    return("Name: "  this.getName() 
          ".\nSex: "  this.getSex() 
          ".\nScore: "  this.getScore() 
          ".\nRank: "  this.getratting() "."
          );         
}

public static void main(String[] args)
{
  
  Exercise_W28 std = new Exercise_W28("Jullien","male", 9, "RankA");
    System.out.println(std.toString());
} }

Now I want to not put the rank in, but based on the score to determine the rank 1~5 : rankC, 5~7: rankD, 8~10: rankA. I just learned about classes in java and I don't know how to handle it

CodePudding user response:

You can remove the Rank from constructor and basis on the score passed, initialize the Rank value in constructor itself !

For e.g.

public Exercise_W28(String name, String Sex,
               int Score)
{
    this.name = name;
    this.Sex = Sex;
    this.Score = Score;
    // if(score == 5) 
  {
ratting="Rank C" ; //so on and so forth 
}

If the logic is too long, consider defining it in another method which returns Rank in String form!

  • Related