Printing multiple objects in different classes - java

The details in this example isn't that important just trying to figure out how I can solve this, I have 3 separate classes Person , Interests and Location. all are objects, a person would have an list of interests and each interest will have a list of locations, i'm using a toString to print my person object and the interest but I can't figure out how to print out the locations of each interest. Do i need to overload my toString?
public class Person{
private String name;
private ArrayList<Interest> interests = new ArrayList<Interest>();
public Person(String name, ArrayList<Interest> interests) {
this.name = name;
this.interests = interests;
}
public void addInterest(Interest newInterest) {
interests.add(newInterest);
}
public Interest getInterest(int indexOfInterest) {
return interests.get(indexOfInterest);
}
public ArrayList<Interest> getInterests() {
return interests;
}
public String getName() {
return name;
}
public String toString() {
String result = getName() + " ";
for(Interest interest : interests) {
result += interest.getName() + "(" + interest.getDangerRating() + ")" + " ";
}
return result.trim();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Interest {
private int dangerRating;
private String name;
private ArrayList<Location> location = new ArrayList<Location>();
public Interest (int dangerRating, String name, ArrayList<Location> location) {
this.dangerRating = dangerRating;
this.name = name;
this.location = location;
}
public int getDangerRating() {
return dangerRating;
}
public String getName() {
return name;
}
}
////////////////////////////////////////////////////////////////
public class Location {
private String location;
public Location (String location){
this.location = location;
}
public String getLocation() {
return location;
}
}

I reccomend making a toString for each class. That way you can call a Location toString in the Intrest's toString, then the location toString in the Person. Also, the ArrayList class has its own toString that prints all the items in the array.
Currently you only have one toString and you are manualy getting the data for each. So for example:
(In the Location Class):
#Override
public String toString()
{
return "Location: " + location;
}
(In the Interest Class):
#Override
public String toString()
{
return "Danger Rating: " + dangerRating +
"Name: " + name +
"Location: " location.toString(); //Note, the name location is confusing here since it is an ARRAYLIST of locations.
}
(In the Person Class):
#Override
public String toString()
{
return "Name: " + name +
"Intrests: " + intrests.toString();
}
(In the Main Class):
public static void main(String[] args)
{
Intrest[] intrests = new Intrest[4]; //TODO: Create intrests, currently they are all null.
Person thePerson = new Person("Eddie", intrests);
System.out.println("Person Info: " + thePerson.toString());
}

Learn to use your tools: every IDE can generate an overriden toString() method and they are good for the most cases.
public class Location {
// ...
#Override
public String toString() {
return "Location{" +
"location='" + location + '\'' +
'}';
}
}
public class Interest {
// ...
#Override
public String toString() {
return "Interest{" +
"dangerRating=" + dangerRating +
", name='" + name + '\'' +
", location=" + location +
'}';
}
}
class Person{
// ...
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", interests=" + interests +
'}';
}
}
I would advise you to stick to your IDE's default toString()s, because that will make your toString()'s look consistent acros all your projects, and soon they will be familiar for you and easy to read.

In your Person class, you call interest.toString() in a loop for all interests
public String toString() {
String result = getName() + " ";
for(Interest interest : interests) {
// add this function to print interest stuff
result += interest.toString();
}
return result.trim();
}
In your Interest class, you'll want a toString or similar method like so
public String toString(){
String s = "";
//print stuff for interest i.e. s+= what you want to add
//loop through locations associated with Interest
for(Location l : this.location ){
// print what you want in location.toString()
// add this funciton to your Location class
s += l.toString()
}
return s;
}
And then in your Main you just need to call
person.toString() and it will loop through and print everything for you.

Related

New to Java, and trying to solve the main part of the exercise for the OldMacdonald Had a Farm song

I am trying to code a song using polymorphism, but I am quite new to Java coding and have a really basic experience. I could use some help with the classes, but my biggest problem is that I do not know how to write the main part of the code, I'd be very grateful if someone could help me with it.
Here is what I have so far
public class OldMacdonald {
public interface Farm{
public String getName();
public String getNoise();
}
class Dog implements Farm{
String name;
String noise;
public Dog(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Cat implements Farm{
String name;
String noise;
public Cat(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Duck implements Farm{
String name;
String noise;
public Duck(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Cow implements Farm{
String name;
String noise;
public Cow(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Pig implements Farm{
String name;
String noise;
public Pig(String name, String noise) {
name=name;
noise=noise;
}
public String getName() {
return name;
}
public String getNoise() {
return noise;
}
}
class Song{
private Farm [] animal = new Farm[5];
Song() {
animal[0] = new Dog("dog", "woof");
animal[1] = new Cat("cat", "meow");
animal[2] = new Duck("duck", "quack");
animal[3] = new Cow("cow", "moo");
animal[4] = new Pig("pig", "oink");
}
public void lyrics() {
int i;
for(i=0; i<animal.length; i++) {
System.out.println("Old MacDonald had a farm, E I E I O,\r\n" +
"And on his farm he had a " + animal[i].getName() + ", E I E I O.\r\n" +
"With a " + animal[i].getNoise() + " " + animal[i].getNoise() + " here and a " + animal[i].getNoise() + " " + animal[i].getNoise() + " there,\r\n" +
"Here a " + animal[i].getNoise() + ", there a " + animal[i].getNoise() + ", evrywhere a " + animal[i].getNoise() + " " + animal[i].getNoise() + ".\r\n" +
"Old MacDonald had a farm, E I E I O.\r\n\r\n");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
You need to "launch" your code somehow, in a Java standalone program like this that would be done from the main method:
public static void main(String[] args)
It looks like Song is your class that actually starts everything off so you need to create an instance of that:
public static void main(String[] args) {
Song mySong = new Song();
}
The lyrics are output by the lyrics() method, so we need to call that:
public static void main(String[] args) {
Song mySong = new Song();
mySong.lyrics();
}
You'll want to tweak your Song() constructor method too:
public Song() {
You might want to update your constructors in animal classes too, you were assigning the parameter to itself (easily done when using same names for variables in params and private fields):
public Cat(String name, String noise) {
this.name = name;
this.noise = noise;
}
If I understood you correctly, in your main()method you just have to create an instance of Song and call lyrics() on it, no? That will populate the Farm array with the animals and call the appropriate methods when printing the lyrics.

Trying to get my show-method to work (Non static method cannot be referenced from static context)

Sorry, I am very new to programming for university. This is a practise question for our test and is set up on code runner. The entire main method and all the classes, methods, constructors and variables were already give to me and I have to make the shown class to print out what I have written. But Bride.getAge() and Location.getSuburb() in the println will not work. Do I need to add something else in?
public class Location {
public static void main(String[] args) {
Bride person = new Bride("Amy Cronos", 29);
Location place = new Location("Tonsley", "South Rd");
Wedding wed = new Wedding(person,place);
show(wed);
}
public static void show(Wedding wed){
System.out.println("Wedding data:" );
System.out.println("Bride: " + wed.getBride() + ", age: " + Bride.getAge);
System.out.println("Location: " + wed.getPlace() + ", suburb: " + Location.getSuburb());
}
private String suburb;
private String street;
Location(String suburb, String street){
this.suburb = suburb;
this.street = street;
}
public String getSuburb(){
return suburb;
}
public String getStreet(){
return street;
}
public class Bride {
private String name;
private int age;
Bride(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
public class Wedding {
private Bride person;
private Location place;
Wedding(Bride person, Location place){
this.person = person;
this.place = place;
}
public Bride getPerson(){
return person;
}
public Location getPlace(){
return place;
}
}
}
You need to correct the below lines in show method
System.out.println("Bride: " + wed.getBride() + ", age: " + wed.getPerson().getAge());
System.out.println("Location: " + wed.getPlace() + ", suburb: " + wed.getPlace().getSuburb());
Since you are using Class names with methods, Bride.getAge() and Location.getSuburb(), these methods are considered static. Hence the error. Since these are not static methods, you need to use the objects of the class to access them rather than Class names.
you have passed object of class Bride and Location so you need to get value like below code : Try with below code and try to understands object in java , static is different thing .
public static void show(Wedding wed){
System.out.println("Wedding data:" );
System.out.println("Bride: " + wed.getPerson() + ", age: " + wed.getPerson().getAge());
System.out.println("Location: " + wed.getPlace() + ", suburb: " + wed.getPlace().getSuburb());
}

Creating multiple tables using SugarORM gives IllegalStateException

I have two classes, Inventory and Recipe. The problem I have is that I cannot add items to the Recipe table. I get the following error message:
java.lang.IllegalStateException:
Caused by: android.database.sqlite.SQLiteException: table RECIPE has no column named NAME (code 1): , while compiling: INSERT OR REPLACE INTO RECIPE(ID,INGREDIENTS,HOW_TO,NAME) VALUES (?,?,?,?)
This happens when I launch the method goToSearchResults(View view), located in MainActivity.
Inventory looks as follows:
import com.orm.SugarRecord;
public class Inventory extends SugarRecord {
String foodType;
String foodName;
String foodQuantity;
public Inventory(){
}
public Inventory(String foodType, String foodName, String foodQuantity) {
this.foodType = foodType;
this.foodName = foodName;
this.foodQuantity = foodQuantity;
}
public String getFoodType() {
return foodType;
}
#Override
public String toString() {
return foodType +
" " + foodName + '\'' +
" " +foodQuantity + '\''
;
}
public void setFoodType(String foodType) {
this.foodType = foodType;
}
public String getFoodQuantity() {
return foodQuantity;
}
public void setFoodQuantity(String foodQuantity) {
this.foodQuantity = foodQuantity;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this. foodName = foodName;
}
}
The class Recipe looks as follows.
import com.orm.SugarRecord;
public class Recipe extends SugarRecord {
String name;
String ingredients;
String howTo;
public Recipe() {
}
public Recipe(String name, String ingredients, String howTo) {
this.name = name;
this.ingredients = ingredients;
this.howTo = howTo;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public String getHowTo() {
return howTo;
}
public void setHowTo(String howTo) {
this.howTo = howTo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Recipe{" +
"name='" + name + '\'' +
", ingredients='" + ingredients + '\'' +
", howTo='" + howTo + '\'' +
'}';
}
}
When I try to add items to the Inventory table, I use the following two lines:
inventory = new Inventory(foodType, foodName.getText().toString(), foodQuantity.getText().toString());
inventory.save();
This works fine. Items are added to Inventory in the way that I want them to.
However, when I try to put items into the Recipe table, using the following two lines (initialized in the main activity). In the main activity, I have a method, which is a dummy method used for debugging purposes.
public void goToSearchResults(View view){
Intent intent = new Intent(this, SearchResults.class);
recipe = new Recipe("Filet Mignon", "Beef, Potatoes", "Use the owen to cook the potatoes real good -_^");
recipe.save();
startActivity(intent);
}
Why doesn’t this work? To me, it seems like the two classes and their usage are identical to each other, and only one works.
Please try my suggestion hope it works :
Update your Sugar to the latest version which is 1.5 here
Try to modify your manifest configure : like modify the name of the database, and correct the location of your class entities. here
I solve my issue following the steps above.

Why is my program returning null,null,0 ,0?

My program is supposed to store the info submitted by the users into another class. It is then supposed to perform a small calculation to determine age. The final part is to create an instance of the secondary class in the Driver and then print out all the info using toString. My results are null, null, 0 ,0 everytime. What am I doing wrong?
public class CustomerInfoProgram {
public static Scanner scan = new Scanner(System.in);
public static String firstName;
public static String lastName;
public static String address;
public static String phoneNumber;
public static int dob;
public static int currentYear;
public static int age;
public static String name;
public static void main(String[] args) {
Customer in = new Customer();
getCustomerName();
getPhone();
getAddress();
getDOB();
getCurrentYear();
in.toString();
}
public static String getCustomerName() {
System.out.println("What is your first name?");
firstName = scan.nextLine();
System.out.println("What is your last name?");
lastName = scan.nextLine();
name = firstName + " " + lastName;
return name;
}
public static String getAddress() {
System.out.println("What is your address?");
address = scan.nextLine();
return address;
}
public static String getPhone() {
System.out.println("What is your phone number?");
phoneNumber = scan.nextLine();
return phoneNumber;
}
public static int getDOB() {
System.out.println("What year were you born?");
dob = scan.nextInt();
return dob;
}
public static int getCurrentYear() {
System.out.println("What is the current year?");
currentYear = scan.nextInt();
return currentYear;
}
}
Secondary class:
import java.util.Scanner;
public class Customer {
public static int age;
public static String allInfo;
public static String name = CustomerInfoProgram.name;
public static String address = CustomerInfoProgram.address;
public static String phoneNumber = CustomerInfoProgram.phoneNumber;
public static int dob = CustomerInfoProgram.dob;
public static int currentYear = CustomerInfoProgram.currentYear;
private int getAge() {
age = (currentYear - dob);
return age;
}
public String toString() {
getAge();
allInfo = (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
System.out.println(allInfo);
return toString();
}
}
public static String name = CustomerInfoProgram.name;
This only sets the value of CustomerInfoProgram.name when the field is initialized, i.e. once, when the Customer class is loaded - it does not update when CustomerInfoProgram.name is updated.
The Customer class is (at the latest) loaded when you call new Customer(), which happens before you run any methods to set the value of CustomerInfoProgram.name, so it is null when you attempt to use name.
If you want to use the current value of CustomerInfoProgram.name, just refer to that field directly. Alternatively, you can add a getter, which will return its current value:
public static String getName() {
return CustomerInfoProgram.name;
}
then call the getter in place of name:
allInfo = (getName() + " " + ...
(Exactly the same applies to the other fields).
You also will get a StackOverflowError from you toString() method:
public String toString() {
getAge();
allInfo = (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
System.out.println(allInfo);
return toString();
}
You are unconditionally calling toString() inside toString(), so this will just keep calling itself until it runs out of stack space.
Instead, just return allInfo:
public String toString() {
getAge(); // This actually does nothing - do you intend to use it in the return value?
return (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
}
and call System.out.println in your main method:
System.out.println(in); // Implicitly calls toString().
See #Andy's answer for the cause of your problem.
The usual approach to this would be to collect the values to be stored in your Customer object before you create it, then use a nondefault constructor call. A partial example might look like this:
// get individual values here
getCustomerName();
getPhone();
// etcetera
Customer in = new Customer(name, phone, address, dob);
The rest I leave as an exercise for the reader.
Being static attributes the initialization in both the classes would be only once. So post you get the input from user those values are not set to the attributes. Hence the null.

Error while trying to print out arraylist

The error I am reviving is "void type is not allowed here " how would I fix this error in order to print out my array list.
import java.util.ArrayList;
public class Library
{
private ArrayList<Member>listOfMembers;
public Library()
{
listOfMembers = new ArrayList<Member>();
}
public void storeMember(Member Member)
{
listOfMembers.add(Member);
}
public int numberOfMembers()
{
return listOfMembers.size();
}
public void listMembers()
{
for (int item=0; item<listOfMembers.size(); item++ ) {
Member m = listOfMembers.get (item);
System.out.println(m.GetWholeName());
}
}
}
and here is my member class just in case you need it
class Member
{
// The fields.
private String firstname;
private String lastname;
private Integer number;
private Integer id;
/**
hehe
*/
public Member(String firstName, String lastName, Integer telNumber, Integer memberId)
{
firstname = firstName;
lastname = lastName;
number = telNumber;
id = memberId;
}
// Add the methods here ...
public void GetWholeName(){
System.out.println(firstname + (" ") + lastname);
}
}
I'm trying to print the first and last name of my member class by using an array list in my library class
You are trying to print out the result of m.GetWholeName() which returns void. Change GetWholeName to return a String instead, or simply call GetWholeName as it's already printing the name to standard out although that behavior doesn't quite match up to the behavior the name would imply.
public String GetWholeName() {
return firstname + " " + lastname;
}
In Member class change this:
System.out.println(firstname + (" ") + lastname);
to this:
return firstname + " " + lastname;

Categories

Resources