HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Java practise exam question

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
practisequestionexamjava

Problem

Doing practise questions for a Java exam which have no answers (useful) I have been asked to do the following:

Write a class called Person with the following features:

  • a private int called age;



  • a private String called name;



  • a constructor with a String argument, which initialises name to the received value and age to 0;



  • a public method toString(boolean full). If full is true, then the


method returns a string consisting of the person’s name followed by their
age in brackets; if full is false, the method returns a string consisting of
just the name. For example, a returned string could be Sue (21) or Sue;

  • a public method incrementAge(), which increments age and returns the


new age;

  • a public method canVote() which returns true if age is 18 or more and


false otherwise.

My code is as follows can someone point out any errors?

public class Person
{
    private int age;
    private String name;

    public Person(String st)
    {
      name = st;
      age = 0;
    }

   public String toString(boolean full)
   {
     if(full == true)
     {
        return name + "(" + age + ")";
     }
     else
     {
        return name;
     }
   }

   public int incrementAge()
   {
      age++;
      return age;
   }

   public boolean canVote()
   {
     if(age >= 18)
     {
        return true;
     }
     else
     {
        return false;
     }
   }
}

Solution

instead of

if(full == true)


use

if (full)


and instead of

if(age >= 18)
{
   return true;
}
else
{
   return false;
}


use:

return age >= 18

Code Snippets

if(full == true)
if(age >= 18)
{
   return true;
}
else
{
   return false;
}
return age >= 18

Context

StackExchange Code Review Q#4979, answer score: 15

Revisions (0)

No revisions yet.