patternjavaModerate
Java practise exam question
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
method returns a string consisting of the person’s name followed by their
age in brackets; if
just the name. For example, a returned string could be
new age;
My code is as follows can someone point out any errors?
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; if
full is false, the method returns a string consisting ofjust 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 returnstrueifageis18or 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
use
and instead of
use:
if(full == true)use
if (full)and instead of
if(age >= 18)
{
return true;
}
else
{
return false;
}use:
return age >= 18Code Snippets
if(full == true)if(age >= 18)
{
return true;
}
else
{
return false;
}return age >= 18Context
StackExchange Code Review Q#4979, answer score: 15
Revisions (0)
No revisions yet.