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
calledage
; - a
private String
calledname
; - a constructor with a
String
argument, which initialisesname
to the received value andage
to0
; - a public method
toString(boolean full)
. Iffull
istrue
, then the method returns a string consisting of the person’s name followed by their age in brackets; iffull
isfalse
, 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 returnstrue
ifage
is18
or more andfalse
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;
}
}
}