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 intcalledage; - a
private Stringcalledname; - a constructor with a
Stringargument, which initialisesnameto the received value andageto0; - a public method
toString(boolean full). Iffullistrue, then the method returns a string consisting of the person’s name followed by their age in brackets; iffullisfalse, the method returns a string consisting of just the name. For example, a returned string could beSue (21)orSue; - a public method
incrementAge(), which increments age and returns the new age; - a public method
canVote()which returnstrueifageis18or more andfalseotherwise.
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;
}
}
}