Creating an ArrayList that combines fields from two objects? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am new to Java and am using BlueJ.
Overview of the context of the program.
I am trying to create a Club Database (arraylist, not actual database) where the user can add a new climber (name, age, gender) and which mountain they've climbed (name, height) to the arraylist.
I've created the Climber class and the mountain class. I've also created an ArrayList for the climbers and can add to this array. My question is.. How can I add a climber to the climber ArrayList, and be able to add which mountain they've climbed and its height at the same time?
The method of adding a climber needs to access both the Climber and Mountain class? Do I need to pass the fields from the Mountain class into Climber?
Whilst code solving the issue is appreciated, would be helpful if I was shown in the right direction so I can understand it more!
Thanks.
import java.util.ArrayList;
import java.util.Scanner;
/**
* Write a description of class ClubStats here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class ClubStats
{
// An ArrayList for storing climber details.
private ArrayList<Climber> climbers;
/**
* Constructor for objects of class ClubStats
*/
public ClubStats()
{
// Initialise instance variables.
climbers = new ArrayList<Climber>();
}
public void addClimber(Climber newName)
{
climbers.add(newName);
}
public Climber getClimber(String name)
{
Climber foundClimber = null;
int index = 0;
boolean searching = true;
while(searching && index < climbers.size()) {
Climber climber = climbers.get(index);
if(climber.getName().equals(name)) {
searching = false;
foundClimber = climber;
}
else {
System.out.println(name + " not found");
index++;
}
}
return foundClimber;
}
public void displayList()
{
for (int item = 0; item<climbers.size();
item++) {
Climber climber = climbers.get(item);
System.out.println(climber.getName() + (" ") + climber.getAge() + (" ")
+ climber.getGender());
}
}
}
public class Climber
{
// Instance variables.
// The climber name.
private String name;
// The climber age
private int age;
// The climber gender.
private String gender;
/**
* Constructor for objects of class Climber
*/
public Climber (String newName, int newAge, String newGender)
{
// Initialise instance variables.
name = newName;
age = newAge;
gender = newGender;
}
/**
* Accessor method for climber's name.
*/
public String getName()
{
return name;
}
/**
* Set the climber's name.
*/
public void setName(String newName)
{
name = newName;
}
/**
* Accessor method for climber's age.
*/
public int getAge()
{
return age;
}
/**
* Set the climber's age.
*/
public void setAge(int newAge)
{
age = newAge;
}
/**
* Set the climer's gender.
*/
public String getGender()
{
return gender;
}
/**
* Accessor method for climber's gender.
*/
public void getGender(String newGender)
{
gender = newGender;
}
}
public class Mountain
{
// Instance variables.
private double height;
private String name;
/**
* Constructor for objects of class Mountain
*/
public Mountain(String mName, double mHeight)
{
// Initialise instance variables
name = mName;
height = mHeight;
}
/**
* Accessor method for mountain name.
*/
public String getName()
{
return name;
}
/**
* Set the mountain name.
*/
public void setName(String newName)
{
name = newName;
}
/**
* Accessor method for mountain height.
*/
public double getHeight()
{
// put your code here
return height;
}
/**
* Set the mountain height.
*/
public void setHeight(double newHeight)
{
height = newHeight;
}
}

A Climber can contain a List<Mountain> of the Mountaina that this Climber climbed.
You can add an addMountain(Mountain mountain) method to Climber class which would add a Mountain to that List.
You can add a getter method List<Mountain> getMountainList() that would return that List.
This way, for each Climber you have access to the Mountains this Climber has climbed.
Note that if multiple Climbers have climbed the same Mountain, they can all contain a reference to that same Mountain instance in their List<Mountain> (i.e. no need to create a copy of that Mountain instance for each Climber).

Related

Store objects into an ArrayList and print out details made by given maker in a given year

public abstract class Instrument {
private String id;
protected String maker;
private static int count = 0;
public Instrument(String maker)
{
count++;
id = "S" + count;
this.maker = maker;
}
public String getMaker()
{
return maker;
}
public String toString()
{
return "ID: " + id + ", Maker: " + maker;
}
abstract public void play(String music);
}
public class Piano extends Instrument
{
// instance variables - replace the example below with your own
private int year;
/**
* Constructor for objects of class Piano
*/
public Piano(int year, String maker)
{
// initialise instance variables
super(maker);
this.year = year;
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public int getyear()
{
// put your code here
return year;
}
public String toString()
{
return super.toString() + " Year: " + year;
}
public void play(String music)
{
System.out.println("Playing piano: " + music);
}
}
so basically I need to create class MusicShop that stores the Instrument objects in an ArrayList named
instruments. And then define a method to print out the details of all pianos made by a given
maker before a given year.
This is what ive done so far
public class MusicShop
{
// instance variables - replace the example below with your own
private ArrayList<Instrument> Instruments;
/**
* Constructor for objects of class MusicShop
*/
public MusicShop()
{
Instruments = new ArrayList<Instrument>();
}
public int getTotal()
{
return Instruments.size();
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public void printDetailsOfPiano()
{
// put your code here
for(Instrument aInstrument : Instruments) {
System.out.println(Instruments.getTotal);
}
}
}
Not sure how to store objects from abstract class into arraylist and print it details.
An object of type Piano can be added to the instruments without problems:
Piano piano = new Piano(1940, "Belarus");
List<Instrument> Instruments = new ArrayList<>();
Instruments.add(piano);
To print the details of an instrument, you need to do something similar to what you have done for play, you need a method print in Instrument.
Piano will override it.
For example:
public abstract class Instrument {
...
abstract public void print();
}
public class Piano extends Instrument {
...
#Override
public void print() {
System.out.println(getMaker() + " " + getYear() );
}
}
When you want to print the instruments, one way could be:
public void printDetailsOfPiano() {
Instruments.forEach( Instrument::print );
}
By the way, in Java the convention is to have the name of the variable not capitalized:
List<Instrument> instruments = new ArrayList<>();

An ArrayList contains two elements, how to return only the String element?

I'm pretty new to Java but I feel like this is an easy task. This arraylist has two elements...names and scores. I want to write a method that prints a list of all the names in the list, not the scores. I know I've done this before I just can't remember how lol
import java.util.ArrayList;
/**
* Print test scrose and student names as well as he average for the class.
*/
public class TestScores {
private ArrayList<Classroom> scores;
public int studentScores;
/**
* Create a new ArrayList of scores and add some scores
*/
public TestScores() {
scores = new ArrayList<Classroom>();
}
/**
* Add a new student and a new score.
*/
public void add (String name, int score) {
scores.add(new Classroom(name, score));
if(score > 100){
System.out.println("The score cannot be more than 100");
}
}
/**
* Return all the student names.
*/
public void printAllNames() {//this is the method.
for (Classroom s : scores){
System.out.println(scores.get(name));
}
}
}
and the classroom class:
import java.util.ArrayList;
/**
* This class creates the names and scores of the students
*/
public class Classroom {
public int score;
public String name;
/**
* Constructor for the Class that adds a name and a score.
*/
public Classroom(String aName, int aScore) {
score = aScore;
name = aName;
}
/**
* Return the name of the students
*/
public String returnName() {
return name;
}
/**
* Return he scores
*/
public int returnScore() {
return score;
}
}
public void printAllNames() {//this is the method.
for (Classroom s : scores){
System.out.println(s.returnName());
}
}
You should be precice in your question, your list does not contain 2 elements - names and scores - but multiple Classroom objects which contain names and scores.
Alternative answer using Java 8 streams:
scores.stream().map(c -> c.returnName()).forEach(System.out::println);

How do you call methods into an object array?

I have two classes. A class called Cat, that holds the cat names, birth year and weight in kilos. I have a class called Cattery that is an array. I want to input cats from the Cat class into the array. Each cat will have its own name, birth year and weight in Kilos. How do I do this? Thank you.
public class Cat {
private String name;
private int birthYear;
private double weightInKilos;
/**
* default constructor
*/
public Cat() {
}
/**
* #param name
* #param birthYear
* #param weightInKilos
*/
public Cat(String name, int birthYear, double weightInKilos){
this.name = name;
this.birthYear = birthYear;
this.weightInKilos = weightInKilo
}
/**
* #return the name.
*/
public String getName() {
return name;
}
/**
* #return the birthYear.
*/
public int getBirthYear() {
return birthYear;
}
/**
* #return the weightInKilos.
*/
public double getWeightInKilos() {
return weightInKilos;
}
/**
* #param the name variable.
*/
public void setName(String newName) {
name = newName;
}
/**
* #param the birthYear variable.
*/
public void setBirthYear(int newBirthYear) {
birthYear = newBirthYear;
}
/**
* #param the weightInKilos variable.
*/
public void setWeightInKilos(double newWeightInKilos) {
weightInKilos = newWeightInKilos;
}
}
The array class.
import java.util.ArrayList;
public class Cattery {
private ArrayList<Cat> cats;
private String businessName;
/**
* #param Cattery for the Cattery field.
*/
public Cattery() {
cats = new ArrayList<Cat>();
this.businessName = businessName;
}
/**
* Add a cat to the cattery.
* #param catName the cat to be added.
*/
public void addCat(Cat name)
{
Cat.add(getName());
}
/**
* #return the number of cats.
*/
public int getNumberOfCats()
{
return cats.size();
}
}
just edit the "addCat" method to pass object from argument to your ArrayList.
public void addCat(Cat name)
{
cats.add(name);
}
It seems that what you are trying to do is add cats to the cats list you declared in your Cattery. Another answer already notes the correction needed - your addCat method must be modified then to actually put the cats in the list. Note that you're not adding the cat name, but an actual Cat object. It also seems like you want the Cattery to have a business name. You can pass that in to the constructor.
public Cattery(String businessName) {
cats = new ArrayList<Cat>();
this.businessName = businessName;
}
...
public void addCat(Cat cat)
{
cats.add(cat);
}
Here's an example of how you may create your cattery and subsequently add cats. You must love cats.
class CatApp{
public static void main(String[] args) {
Cattery cattery = new Cattery("The Delicious Cats Business");
cattery.addCat(New Cat("Milo", 3, 388.87));
cattery.addCat(New Cat("Otis", 2, 1.4));
System.out.println("Total number of cats ready for consumption = "
+ cattery.getNumberOfCats());
}
}

How to create a test class for a java project [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have created a Browser class for my project. I now need to extend this project and therefore need to create a suitable test plan and test class.
How do I create this test class?
/**
* Write a description of class Browser here.
*
* #author (johnson)
* #version (10/12/13)
*/
import java.util.ArrayList;
import java.util.List;
public class Browser
{
// instance variables - replace the example below with your own
private int iD;
private String email;
private int yearOfBirth;
private boolean memberID;
private WineCase wineCase;
private boolean loggedIn;
private Website website;
private boolean discount;
private List<Boolean> baskets = new ArrayList<Boolean>();
/**
* Constructor for objects of class Browser
*/
public Browser()
{
// initialise instance variables
wineCase = null;
website = null;
iD = 00065;
yearOfBirth = 1992;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = 0;
email = newEmail;
yearOfBirth = newYearOfBirth;
loggedIn = false;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(int newID, String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = newID;
email = newEmail;
yearOfBirth = newYearOfBirth;
memberID = true;
discount = false;
}
/**
* returns the ID
*/
public int getId()
{
return iD;
}
/**
* gets the email of the browser class
*/
public String getEmail()
{
return email;
}
public boolean getDiscount()
{
return discount;
}
/**
* gets the yearOfBirth for the browser class
*/
public int yearOfBirth()
{
return yearOfBirth;
}
public double getWineCost()
{
return wineCase.getWineCost();
}
public double getWineCase()
{
return wineCase.getWineCost();
}
/**
* returns
*/
public void setLoginStatus(boolean status)
{
loggedIn = status;
}
/**
* returns
*/
public void selectWineCase(WineCase winecase)
{
wineCase = winecase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+winecase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
/**
* returns
*/
public void payForWine()
{
website.checkout(this);
}
public void setId()
{
iD = 999;
}
public void setWebSite(Website website)
{
this.website = website;
}
public void setDiscount(boolean discount)
{
this.discount = discount;
}
public ArrayList<WineCase> getBasket(WineCase wineCase)
{
this.wineCase = wineCase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+wineCase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
}
Any answers/replies would be greatly appreciated.
You can use a unit testing framework as http://junit.org/. There are numerous examples on the internet.
An example unit test would be:
public class BrowserTest{
#Test
public void testNoArgsConstructor(){
Browser testedBrowser = new Browser();
assertNull(testedBrowser.getWineCase());
assertNull(testedBrowser.getWebsite());
assertEquals(00065, testedBrowser.getId());
assertEquals(1992, testedBrowser.getYearOfBirth());
assertTrue(testedBrowser.getMemberId());
assertFalse(testedBrowser.isDiscount());
}
//more tests
}
If You want to test your class, use JUnit framework - you will create unit tests (http://junit.org/). It is already included in IDE (Eclipse), just go File → New → JUnit → JUnit Test case.

Create several new objects within a for-loop in Java

I want to create several objects from a class in a for loop. but I don't know how to code it. What I have written creates a new object but it overwrites the previous object.
package assginment1_version4;
import java.util.*;
public class Client {
public static void main (String[] args) {
System.out.println ("this is a bill database");
System.out.println ("add a user?(Y/N)");
Scanner input = new Scanner(System.in);
String answer = input.nextLine ();
ArrayList ary = new ArrayList ();
for (int i=1 ; i < 100; i++) {
if (answer.equalsIgnoreCase("y")) {
Bill bill1 = new Bill();
System.out.println("user first name:");
bill1.setFname (input.nextLine());
System.out.println("user Last name:");
bill1.setLname (input.nextLine());
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
} else if (answer.equalsIgnoreCase ("n")) {
if (Bill.getBillCounter () == 0) {
System.out.println ("the Database is empty");
break;
} else {
System.out.println ("Number of Users: "
+ Bill.getBillCounter ());
break;
}
} else {
while (!answer.equalsIgnoreCase ("n")
&& !answer.equalsIgnoreCase ("y")) {
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
}
}
}
}
}
please help me to complete this code.
You're overriding them because you create a new Bill on each loop and never save them off anywhere. I believe you want to add them to your ArrayList:
First, you should add a type to your ArrayList:
ArrayList<Bill> ary = new ArrayList<Bill>();
Then, before you get the input from the user on whether or not to add a new Bill, you should add the current one to this list:
...
System.out.println("user Last name:");
bill1.setLname(input.nextLine());
ary.add(bill1);
...
You haven't used the ArrayList, you need to add the Bill's objects at the end of the for loop.
ary.add(bill1);
and add a type to your ArrayList
ArrayList<Bill> ary = new ArrayList<Bill>();
This is the Bill class.....
package assginment1_version2;
public class Bill {
/**
* Attributes of a bill
*/
private String firstName;
private String lastName;
private int paymentDeadline;
private int paymentCode;
private int billCode;
/**
* Attribute of Bill Class
*/
private static int BillCounter=0;
/**
* Methods of Bill class
* #return number of users
*/
/*public static int getBillCounter(){
return BillCounter;
}*/
/**
* Class Constructor
* #param Fname is the first name of user
* #param Lname is the last name of user
* #param Pdeadline is the deadline of paying the bill
* #param Pcode introduces the payment uniquely
* #param Bcode introduces the bill uniquely
*/
public Bill (){
BillCounter++;
}
/**
* FirstName methods
* method to set FirstName
* #param n is the input of setname method as a user name
*/
public void setFname (String n){
firstName=n;
}
// method to get FirstName
public String getFname (){
return firstName;
}
/**
* LastName methods
* method to set LastName
*/
public void setLname (String m){
lastName=m;
}
// method to get LastName
public String getLname(){
return lastName;
}
/**
* PaymentDeadline methods
* method to set PaymentDeadline
*/
public void setPaymentDeadline(int m){
paymentDeadline= m;
}
//method to get PaymentDeadline
public int getPaymentDeadline(){
return paymentDeadline;
}
/*
* PaymentCode methods
* Method to set PaymentCode
*/
public void setPaymentCode (int m){
paymentCode=m;
}
//method to get PaymentCode
public int getPaymentCode(){
return paymentCode;
}
/*
* Methods of BillCode
* method to set BillCode
*/
public void setBcode(int Bcode){
billCode=Bcode;
}
//method to get BillCode
public int getBcode(){
return billCode;
}
}

Categories

Resources