I have been putting together a Drive Tester to test a class I have been working on for an assignment, but I have hit a dead end with the tester and I am not sure how to finish it up and remove any errors.
Here is the tester:
public class PersonTester
{
public static void main(String[] args)
{
System.out.println("PersonClassTester");
System.out.println("*****************");
System.out.println("");
Person joeSmith = new Person();
String "smith" = joeSmith.setSurName(); // All these statements with set surname and forname etc are apperantly not statements and require a semi-colon, even though they are there.
String "joe" = joeSmith.setForName();
int 25 = joeSmith.setAge();
double 1.57 = joeSmith.setHeight();
String "male" = joeSmith.setGender();
joeSmith.toString();
joeSmith.format();
}
}
The main issue with this is that the Netbeans client is stating that the setter statements highlighted are not actually statements, and are saying that it needs a semi-colon for each of them despite them actually being there. It is also saying that there are no formal or actual arguments. I know what they are but I'm getting confused on them regardless.
And this is the class I need to run through the tester:
public class Person
{
private String surName;
private String forName;
private int age;
private double height;
private String gender;
#Override
public String toString()
{
return getClass().getName() + "[surName= " + surName + " forName= " + forName + " age= " + age + " height= " + height + " gender " + gender + "]";
}
public void format()
{
System.out.format("%10s%10s%10d%10f%10s", surName, forName, age, height, gender);
}
public String getSurName()
{
return surName;
}
public String getForName()
{
return forName;
}
public int getAge()
{
return age;
}
public double getHeight()
{
return height;
}
public String getGender()
{
return gender;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public void setForName(String forName)
{
this.forName = forName;
}
public void setAge(int age)
{
this.age = age;
}
public void setHeight(double height)
{
this.height = height;
}
public void setGender(String gender)
{
this.gender = gender;
}
}
Any advice on getting the class tester to function properly? Once the tester works the rest of the assignment shouldnt be much of a problem.
Edit: The program compiles, but is unable to print the String statements.
PersonClassTester
*****************
surName forName 25 1.570000 gender
String "smith" = joeSmith.setSurName(); is not correct syntax. It should look like this:
joeSmith.setSurName("smith")
This tells Java to execute the method setSurName() on the object joeSmith, with the given string as an argument.
The same goes for the rest of your assignments in main.
Your setter method looks like:
public void setSurName(String surName)
{
this.surName = surName;
}
Which says your setter is not going to return anything and it expects one parameter which is of String type.
Now here's how you are using your setter method:
String "smith" = joeSmith.setSurName();
So here it means you are expecting a surname from setter which is one part of compiler error that you see. And as stated, it expects a string argument and you are not passing it and that's another part of compiler issue.
So you may want to change it to:
joeSmith.setSurName("smith");//similar changes with other setter method.
Which means, now you are passing string argument and not expecting anything in return by calling this method and hence Compiler would be happy with this.
Related
I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();
I am just starting to get into Object Oriented Programming in Java. I am curious about what the difference (if any) is between the 2 pieces of code below.
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
This is the 2nd piece of code;
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
I prefer the 2nd piece of code here because its clearer to understand but I have been reading a lot on methods and objects and I can't figure out what the actual differences are. Are set and get methods secure ways of entering values?
Let's start with what you think is the simpler code:
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
We could instantiate this class and use it like so:
public static void main(String[] args) {
BuyAHouseInc buyAHouseInc = new BuyAHouseInc();
buyAHouseInc.displayClient("jane", "doe", "123 main street", 100000);
}
The effect of this main method is to display the information on your screen. That's everything instances of this class can do. You can't share the information, or reuse it.
The first piece of code you show lets you create an object with fields that store data that you can reuse. The getters and setters are written so you can access those fields to use elsewhere in your program.
We can also add the displayClient method to this class, like so:
public class BuyAHouseInc {
private String firstName;
private String surname;
private String address;
private int budget;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
...
public void displayClient() {
System.out.println("Client Name: " + this.firstName + " " + this.surname);
System.out.println("Address: " + this.address);
System.out.println("Budget: " + "€" + this.budget);
}
}
So then I might be able to write a program like this:
public class Solution {
public static void main(String[] args) {
BuyAHouseInc jane = new BuyAHouseInc("jane", "doe", "123 main street", 100000);
BuyAHouseInc john = new BuyAHouseInc("john", "doe", "123 main street", 50000);
System.out.println("The following clients can afford to buy a house");
if (canAffordTheHouse(jane)) {
jane.displayClient();
}
if (canAffordTheHouse(john)) {
john.displayClient();
}
}
public static boolean canAffordTheHouse(BuyAHouseInc client) {
return client.getBudget() > 50000;
}
}
If you're asking about getter / setter vs direct access, then there are many advantages of getter / setter over direct access.
Basically:
It's more secure as variable implementations should be kept private
and non accessible by public sources.
It allows for additional functionality in the get / set call and
allowing different behavior for whom is getting / setting.
It allows for different access levels (public, protected, etc.)
It is, however, the exact same speed as accessing directly.
Here is another answer that shows what I said in more detail.
You could combine the blocks of code
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
public void displayClient()
{
System.out.println("Client Name: " + this.firstName + " " + this.surname);
System.out.println("Address: " + this.address);
System.out.println("Budget: " + "€" + this.budget);
}
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
Alternatively, you could pass a whole object of BuyAHouseInc into the display function.
public void displayClient(BuyAHouseInc b)
{
System.out.println("Client Name: " + b.getFirstName()+ " " + b.getSurname());
System.out.println("Address: " + b.getAddress());
System.out.println("Budget: " + "€" + b.getBudget());
}
public void displayClient(String firstName, String surname, String address, int budget)
{
//........
}
is simply another method. Enclosed in { and } defines what it does when a call to displayClient() method is called. displayClient() requires 3 arguments before it can perform it's task. The arguments are what's inside the () in public void displayClient(String firstName, String surname, String address, int budget). The 2nd piece of code can be put within the public class BuyAHouse block or { }. Your setters() and getters() are also similar to displayClient() but has fewer arguments.
What's inside { } of public class BuyAHouse are members or methods. These methods has access to the class variables
private String firstName;
private String surname;
private String address;
private int budget;
That's why on most of the syntax of setters(), you can see that it's setting/assigning/storing (whatever you like) values to your class variables. So basically set() methods are used to modify the value of the variables firstname, surname,address and budget
getters() are used to return the value of the variables.
For instance,
String name; //this has no string value yet
//function definition - you tell what you want this method to do
public void setMyName(String yourName){
name = yourName; //you store the value of yourName to name
}
//method call
setMyName("whatever name you like"); // whatever name you like will be passed to the yourName variable
I have just started doing object oriented programming as part of my course, but I am struggling with it, specifically the toString method in a Person Class. I need to write a toString() method to display the contents of instance variables.
I need to by sample print out:
Person[forName=joe, surname= smith, age= 25, height= 1.57, gender= male]
I also need to format it like this using the format method:
smith joe 25 1.57 male
davis sian 18 1.73 female
*** *** *** *** ***
I havent written a tester yet, but here is what I have written so far for the class and now I'm stuck, I'm not even sure if I am getting the toString statement wrong. I am using netBeans for this:
public class Person
{
private String surname;
private String forname;
private int age;
private double height;
private String gender;
public String toString()
{
return getClass().getName() + "[surname= " + surname + " forname= " + forname + " age= " + age + " height= " + height + " gender " + gender + "]";
}
}
What I need to do is make a class called Person that I can test. It needs to be able to hold the five variables above (surname etc) for different people. I need to be able to print out each of the instance variables with a toString() method and to use a format() method to produce a string with formatting infomation in order for the string printed out by the toString() method to be formatted like the second quotation.
Am I on the right track and regardless, how can I work through this?
EDIT: I have looked at the Person Class and have done what I can with it, does it seem decent enough? I am going to try and get a PersonTester together.
public class Person
{
private String surName;
private String forName;
private int age;
private double height;
private String gender;
#Override
public String toString()
{
return getClass().getName() + "[surName= " + surName + " forName= " + forName + " age= " + age + " height= " + height + " gender " + gender + "]";
}
public void format()
{
System.out.format("%10s%10s%10d%10f%10s", "surName", "forName", age, height, "gender");
}
public String getSurName()
{
return surName;
}
public String getForName()
{
return forName;
}
public int getAge()
{
return age;
}
public double getHeight()
{
return height;
}
public String getGender()
{
return gender;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public void setForName(String forName)
{
this.forName = surName;
}
public void setAge(int age)
{
this.age = age;
}
public void setHeight(double height)
{
this.height = height;
}
public void setGender(String height)
{
this.gender = gender;
}
}
EDIT 2: Started on a class Tester, but I am running into errors again about the setter's not having a ; and not being a statement.
Here's the tester so far:
public class PersonTester
{
public static void main(String[] args)
{
System.out.println("PersonClassTester");
System.out.println("*****************");
System.out.println("");
Person joeSmith = new Person();
String "smith" = joeSmith.setSurName();
String "joe" = joeSmith.setForName();
int 25 = joeSmith.setAge();
double 1.57 = joeSmith.setHeight();
String "male" = joeSmith.setGender();
joeSmith.toString();
joeSmith.format();
}
}
First of all you have to noticed that every object you create extends class Object. This Object class contains methods like toString, equals, hashCode...
your object have also this methods(inherited from Object). When you override (you should annotate this method with #Override) for eg. toString you will always use this toString method instead of inherited one. Its called polymorphism. Your toString method looks fine. In your main method you should use some kind of loop through all Persons and there format the output from toString method.
You have error in your code
public String toString(); {
remove the ; after ()
public class Main {
public static void main(String[] args) {
Person a = new Person("smith", "joe", 25, 1.57, "male");
Person b = new Person("davis", "sian", 18, 1.73, "female");
List<Person> persons = new ArrayList<Person>();
persons.add(a);
persons.add(b);
for(Person p : persons){
System.out.format("%s %s %s %d %.2f %s", p.getClass().getName(), p.getSurname(), p.getForname(), p.getAge(), p.getHeight(), p.getGender());
System.out.println();
}
}
}
If you call this
System.out.println(p.toString());
than you ll get your person via toString method.
I just edit your Person class and add constructor and geters + seters
public Person(String surname, String forname, int age, double height,
String gender) {
super();
this.surname = surname;
this.forname = forname;
this.age = age;
this.height = height;
this.gender = gender;
}
Here is geter and seter sample.
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
As already mentioned your toString() is fine.
Please note that the toString() method and the format() method are IMO supposed to work independently as they do serve different purposes.
I suggest to put the format method not in the person class (or at least make it static method). This is because a single Person instance has not enough information for it to be printed in the table format. It at least needs to know the column widths. Otherwise you could end up with something like this:
smith joe 25 1.57 male
someVeryLongFirstName sian 18 1.73 female
*** *** *** *** ***
So the format method should take a list of persons that should be printed out and then first calculate the column widths. After this is done you then just pad the property value to the column width and print this out.
You are on the right track:
Inside of the Person class you need to add public methods for each private variable to set the data:
public void setAge(int age) {
this.age = age;
}
Then you can create a Person object in your main class and set his age:
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setAge(15);
}
}
As an alternative, you can use a constructor inside of your Person class to set your object's variables:
public Person(String surname, int age) {
this.surname = surname;
this.age = age;
}
And create the object in the main method like this:
Person p = new Person("Nillas", 25);
You can always run your toString() method in the main class after you've created the object and see the result:
System.out.println(p.toString());
Hope this helps, good luck!
I have a couple to class in which I'm getting and setting a few things and then finally calling it in my main method. But when I call my class in the main method it just gives me the object instead of name,address and age. I know this structure is very complicated but I want to keep this structure because later on I will be adding a lot of things to this. It would be AMAZING if someone could tell me how to do this. I would really appreciate this. Below is my code for all my classes
This is my first class
public class methodOne
{
public String getName()
{
String name = "UserOne";
return name;
}
public int getAge()
{
int age = 17;
return age;
}
public String getAddress()
{
String address = "United States";
return address;
}
}
This is my second class
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my third class
public class methodThree {
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
public methodThree()
{
this.methodOneInMethodThree = new methodOne();
this.methodTwoInMethodThree = new methodTwo(methodOneInMethodThree);
}
public methodTwo getMethodTwoInMethodThree() {
return methodTwoInMethodThree;
}
public void setMethodTwoInMethodThree(methodTwo methodTwoInMethodThree) {
this.methodTwoInMethodThree = methodTwoInMethodThree;
}
}
This is my fourth class which is the method maker
public class methodMaker {
public methodThree brandNewFunction(methodTwo object)
{
methodThree thirdMethod = new methodThree();
thirdMethod.setMethodTwoInMethodThree(object);
return thirdMethod;
}
}
This is my main class which calls methodMaker. What I want to achieve is that when I print the value it should print the name,address and age but instead it just prints trial.methodThree#4de5ed7b
public class mainClass {
public static void main(String args[])
{
methodMaker makerOfMethods = new methodMaker();
methodOne one = new methodOne();
methodTwo object = new methodTwo(one);
System.out.println(makerOfMethods.brandNewFunction(object).toString());
}
}
What you need to do is to override the default implementation of the .toString() method in the objects you want to print out:
#Override
public String toString()
{
return "Name: " + this.name;
}
EDIT:
I do not know exactly where you are printing, and you naming convention doesn't really help out, but from what I am understanding, you would need to implement it in all of you classes since they all seem to be related to each other.
So, in your methodOne class (can also be applied to methodTwo):
#Override
public String toString()
{
return "Name: " + this.name + " Age: " + this.age + " Address: + " this.address;
}
In your methodThree class:
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
#Override
public String toString()
{
StringBulder sb = new StringBuilder();
if(this.methodTwoInMethodThree != null)
{
sb.append("Method 2:").append(methodTwoInMethodThree.toString());
}
if(methodOneInMethodThree != null)
{
sb.append("Method 1:").append(methodOneInMethodThree.toString());
}
return sb.toString();
}
When you call
MyClass myObject = new MyClass();
System.out.println(myObject);
Implicitly , java calls instead
System.out.println(myObject.toString());
So, if in MyClass, you override toString(), then whatever your toString method returns is what's gonna be printed.
Side note: are you confusing classes and methods? Methods are functions in your classes, classes are wrappers around a bunch of attributes and methods. Your naming is confusing.
try this code:
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return name+" "+address+" "+age;
}
}
Are you printing the object using println()?
From the docs, println():
calls at first String.valueOf(x) to get the printed object's string value
This string value is obtained from the object's toString() method, which:
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object
So if you want to print anything other than this you have to override the toString() method in your object and return a string containing whatever you want.
Just google "override tostring java" and you will see a ton of examples.
As per definition toString() returns "Returns a string representation of the object as:
getClass().getName() + '#' + Integer.toHexString(hashCode())
But sometimes I could see even if it is not Overriden in our class, it returns the String associated with it. I mean Object.toString() returns some String but not "ClassName#HexCode".
When does this happen. Please let me know whats the reason behind this ??
It's only possible if a class extends another class with overriden (or inherited overriden) toString().
The default behavior of toString() is to return the object as
getClass().getName() + '#' + Integer.toHexString(hashCode()).
But if you override toString() in base class or child class you can specify the way your object should be printed.
Probably in your case its using the inherited method of your base class .
Ex:
class Person {
private String myName; // name of the person
private int myAge; // person's age
private String myGender; // 'M' for male, 'F' for female
// constructor
public Person(String name, int age, String gender) {
myName = name;
myAge = age;
myGender = gender;
}
public String getName() {
return myName;
}
public int getAge() {
return myAge;
}
public String getGender() {
return myGender;
}
public void setName(String name) {
myName = name;
}
public void setAge(int age) {
myAge = age;
}
public void setGender(String gender) {
myGender = gender;
}
public String toString() {
return myName + ", age: " + myAge + ", gender: " + myGender;
}
}
public class Teacher extends Person {
//...
}
calling `toString();` method will call inherited `tOString()` method of base class and will return `return myName + ", age: " + myAge + ", gender: " + myGender;`