How can I show all objects on java - java

Item.java
I have an item with variables name and weight
package com.company;
public class Item {
String name;
Double weight;
}
Bag.java
the bag can receive up to 20 kg items.
package com.company;
public class Bag {
Item [] myBags;
int itemCount;
Double currentWeight;
Bag(){
itemCount = 0;
currentWeight = 0.0;
myBags = new Item[50];
}
boolean canAddItem(Item item) {
if (currentWeight + item.weight > 20) {
return false;
} else {
return true;
}
}
void AddItem(Item item){
myBags[itemCount] = item;
currentWeight = currentWeight + myBags[itemCount].weight;
itemCount++;
}
}
Main.java
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Bag myBag = new Bag();
/*item 1*/
Item fishing_rod = new Item();
fishing_rod.name = "rod1";
fishing_rod.weight = 10.4;
if(myBag.canAddItem(fishing_rod)){
myBag.AddItem(fishing_rod);}
/*item 2*/
Item axe = new Item();
axe.name = "axe1";
axe.weight = 2.2;
if(myBag.canAddItem(axe)){
myBag.AddItem(axe);}
System.out.println(myBag.currentWeight);
//System.out.println(myBag.myBags); i want to show that's here
}
}
I added two objects to the bag . I want to show all the objects I have added in the bag.
How can I show ? How can I show this in java ?
Thanks for your help

You have to override the toString() method in your class:
For Item class first:
#Override
public String toString() {
return "Name: "+ name + ": weight "+ weight +"Kg";
}
then for Bag class
#Override
public String toString() {
return Arrays.toString(myBags);
}
In this way every time you print your bag you will get the content of it.

In Bag class:
public void printBag() {
for(int i =0; i< itemCount; i++) {
System.out.println("Name: " + myBags[i].name);
System.out.println("Weight: " + myBags[i].weight);
}
}
In main method:
myBag.printBag();

Define a function inside your Bag class:
public void printBag() {
for(Item element : myBags) {
System.out.println('Name: ' + element.name);
System.out.println('Weight: ' + element.weight);
}
}
And call it from the main:
myBag.printBag();

Related

How to assign values to an array?

Ok, I'm trying to create a hamburger object, it has to have an array of toppings and other things. I keep getting a compilation error every time I try to assign values to the array for each object. Here's the class
/*
This Hamburger class is to define how to make a Hamburger sandwich
Then this class will be used to create a Hamburger object in the tester class
Fields & their purpose
4. toppings – an array of Strings storing the toppings on the burger.
*/
public class Hamburger {
//declear private fields
private int weight;
private String doneness;
private boolean cheese;
private String[] toppings;
//creat arrays for each object, then use it in each specific object
//String[] hamburgerToppings = {"l", "m"};
//String[] cheseburgerToppings = {"l", "m"};
//String[] anotherCheseburgerToppings = {"l", "m"};
//create printable array of toppings
//full constructor
public Hamburger(int weightOZ, String done,
boolean WantCheese, String[] topps) {
weight = weightOZ;
doneness = done;
cheese = WantCheese;
toppings = topps;
}
//overloaded no-arg constructor
public Hamburger(){
}
//copy constructor
public Hamburger(Hamburger burger){
weight = burger.weight;
doneness = burger.doneness;
cheese = burger.cheese;
toppings = burger.toppings;
}
//declear getter methods
public int getWeight() {
return weight;
}
public String getDoneness() {
return doneness;
}
and here's the tester class
//This class will test & run the Hamburger class
//It has the main method to run the other methods in the Hamburger class
public class HamburgerTester {
public static void main(String[] args) {
//Creating Hamburger objects
Hamburger hamburger = new Hamburger();
Hamburger cheseburger = new Hamburger();
Hamburger anotherCheseburger = new Hamburger(cheseburger);
//Setting Values for hamburger object
hamburger.setWeight(7);
hamburger.setDoneness("Mediuem Rare");
hamburger.setCheese(false);
hamburger.setToppings();
//Setting Values for cheseburger object
cheseburger.setWeight(10);
cheseburger.setDoneness("Well Done");
cheseburger.setCheese(true);
//cheseburger.setToppings();
//anotherCheseburger object is a copy of cheseburger
//there's no need to set special values for it
//Printing Results
System.out.println("Hamburger weight is: " + hamburger.getWeight() +
" doneness: " + hamburger.getDoneness() +
" with/without cheese: " + hamburger.getCheese() +
" Toppings: " + hamburger.getToppings());
System.out.println("cheseburger: " + cheseburger.toString());
System.out.println("cheseburger copy: " + anotherCheseburger.toString());
System.out.println("cheseburger wieght after a bite: " + cheseburger.bite());
System.out.println("cheseburger wieght after a 2 bites: " + cheseburger.bite());
}
}
public boolean getCheese() {
return cheese;
}
public String[] getToppings() {
return toppings;
}
//declear setter methods
public void setWeight(int weightOZ) {
this.weight = weightOZ;
}
public void setDoneness(String done) {
this.doneness = done;
}
public void setCheese(boolean WantCheese) {
this.cheese = WantCheese;
}
public void setToppings(String[] topps) {
this.toppings = topps;
for(int i =0; i < toppings.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(toppings[i]);
}
}
//copy method
public Hamburger copy(){
Hamburger burger = new Hamburger(weight, doneness, cheese, toppings);
return burger;
}
//bite methode
public int bite(){
if (weight > 0)
weight--;
return weight;
}
//toString method to print what each Hamburger contains
public String toString(){
String str = "Weight is: " + weight +
"\nDoneness is: " + doneness +
"\nCheese is: " + cheese +
"\nToppings are: " + toppings;
return str;
}
}
any help is appreciated, thanks!
Ill try to help, What Are you trying to do? Your getter and setter methods for the object Hamburger appear to be in the class Hamburgertester.

save a object inside an arraylist inside the other class

Hi i need help with a personal project. i'm developing a software to manage shows(event), and i have problem to save and object into my arraylist inside class.
i have 3 object, artist,event, contract, every time user sign a contract,between an artist and agent, i want to be able to save the artist into the agentContract inside the agent class. because i need a list of artist for each agent. My problem is every time i try to save than, my program save all the artist in the first agent, only. Can someone help me???
this is my artist class:
public class Agent extends Person implements Serializable {
float dueAmount;
int percentage;
public static ArrayList<Artist> AgentArtists = new ArrayList<Artist>();
public Agent()
{
super();
dueAmount = 0;
percentage = 0;
}
.....
.....
public static ArrayList<Artist> getAgentArtists()
{
return AgentArtists;
}
public void setAgentArtists(Agent age,Artist art)
{
age.AgentArtists.add(art);
}
i'm using this method to sign the contract and save the artist into the artistlist of agent
public void SignWithArtist(Artist art, Agent age)
{
if (age.getAgentArtists().add(art) == true)
{
System.out.println("\n" + art.getName() + " is signing the contract\n");
ProgManage.PauseScreen(1000);
for(int i=0; i<=1; i++)
{
System.out.print("*");
ProgManage.PauseScreen(1000);
System.out.print("**");
ProgManage.PauseScreen(1000);
System.out.print("***");
ProgManage.PauseScreen(1000);
System.out.print("****");
ProgManage.PauseScreen(1000);
}
System.out.println("\nContract signed by " + art.getName());
ProgManage.PauseScreen(1000);
} else {
System.out.println("\n*ERROR* Artist not added");
ProgManage.PauseScreen(1000);
}
}
Try this code :
public class Agent extends Person implements Serializable {
float dueAmount;
int percentage;
public ArrayList<Artist> agentArtists;
public Agent()
{
super();
agentArtists = new ArrayList<Artist>();
dueAmount = 0;
percentage = 0;
}
public ArrayList<Artist> getAgentArtists()
{
return agentArtists;
}
public void setAgentArtists(Artist art)
{
agentArtists.add(art);
}
}

Issue printing array list constructed of defined classes

I am attempting to construct a list of rows which contain cells. The classes row and cell have been defined.
I want to construct the array list and then print it.
My Code:
import java.util.*;
public class findBfs
{
int numWarehouses;
int numCustomers = 4;
ArrayList<Integer[]> warehouses = new ArrayList<Integer[]>();
Integer[] warehouse1 = {3,6,8,2};
Integer[] warehouse2 = {6,1,2,5};
Integer[] warehouse3 = {7,8,3,9};
class Cell {
int cost;
int shipment;
public Cell(int x, int y){
x = cost;
y = shipment;
}
public int getCost(){
return cost;
}
public int getShipment(){
return shipment;
}
public void updateShipment(int newAmount){
shipment = newAmount;
}
}
class Row{
public Row(Integer[] warehouse) {
ArrayList<Cell> row = new ArrayList<Cell>();
for(int value: warehouse) {
row.add(new Cell(value, 0));
}
}
}
ArrayList<Row> tableu = new ArrayList<Row>();
public findBfs()
{
warehouses.add(warehouse1);
warehouses.add(warehouse2);
warehouses.add(warehouse3);
for(Integer[] thisWarehouse : warehouses)
{
tableu.add(new Row(thisWarehouse));
}
}
public void printTableu() {
for(Row thisRow : tableu) {
System.out.println(thisRow);
}
}
}
Currently with the code I have the following gets printed:
findBfs$Row#25ca623f
findBfs$Row#9f8297b
findBfs$Row#36b4f5a
What has happened? :(
You have declared row ArrayList<Cell> type as local to the constructor. Declare it in your class context: which is probably you are wanting.
override the toString() method and provide an implementation in the Row class with proper format you want it to see as String. You will probably need to override toString() method and provide an implementation for the Cell class too.
For a List of specific element, i prefer to declare the list with the element name as prefix and list as suffix: suppose instead of ArrayList<Cell>row, declare it as ArrayList<Cell>cellList
For example:
class Cell {
// your other code
#Override
public void String toString() {
return "shipment: " + shipment + "; cost: " + cost;
}
}
class Row{
ArrayList<Cell> cellList = new ArrayList<Cell>();
public Row(Integer[] warehouse) {
for(int value: warehouse)
cellList.add(new Cell(value, 0));
}
#Override
public void String toString() {
return cellList.toString();
}
}
Edit:
you are assigning the class variable wrongly, constructor_local_var <- class_var: which should be class_var <-- constructor_local_var
public Cell(int x, int y){
cost = x;
shipment = y;
}
class Row{
ArrayList<Cell> row = new ArrayList<Cell>();
public Row(Integer[] warehouse) {
for(int value: warehouse) {
row.add(new Cell(value, 0));
}
}
}
i think doing this and overriding toSting() will help
When an object is printed out, it is converted to a String first, using the toString() method. Since you did not override it, you're getting the default implementation from Object, which, as you can see, is pretty useless.
You should just override it, like you override any other method. E.g.:
class Cell {
// snipped
#Override
public void String toString() {
return "Cell [shipment: " + shipment + "; cost: " + cost + "]";
}
}
class Row {
// snipped
#Override
public void String toString() {
// row.toString() could be simpllified to row - added for clarity.
return "Row: " + row.toString();
}
}
You need to save the warehouse or the row variable in the Row class, depending on what you want to print, and then override the toString() method.
Following is an example implementation of the Row class for the warehouse version.
class Row {
private Integer[] warehouse;
public Row(Integer[] warehouse) {
this.warehouse = warehouse;
ArrayList<Cell> row = new ArrayList<Cell>();
for (int value : warehouse) {
row.add(new Cell(value, 0));
}
}
public String toString() {
return Arrays.asList(this.warehouse).toString();
}
}

Find similar integers inside of an ArrayList with Class Method

I need to iterate through and ArrayList of objects and look for a variable that has the same value for multiple objects. As the example below, I am looking through an ArrayList, that has a sub-class . All I want to do is find out if a house or condo share the same listing number for this example code. I tried using a double loop, and an enhanced loop with a method (sameListingNum) and am having trouble working it out.
Thank you
// main client class
public static void main(String[] args)
{
ArrayList<House> listings = new ArrayList();
listings.add(new House(0001, 200000.00));
listings.add(new House(0201, 200000.00));
listings.add(new House(0001, 200000.00));
listings.add(new House(0401, 200000.00));
listings.add(new House(0031, 200000.00));
listings.add(new Condo(0401, 200000.00, 4));
listings.add(new Condo(0001, 120000.00, 3));
listings.add(new Condo(0301, 220000.00, 2));
listings.add(new Condo(0001, 130000.00, 3));
listings.add(new Condo(0201, 130000.00, 3));
for(House currentHouse: listings)
System.out.println(currentHouse);
for(int i=0; i<listings.size()-1; i++)
{
for(int j=i+1; j<listings.size(); j++)
{
}
}
// House Class
public class House
{
public int listingNum;
public double price;
public House()
{
listingNum = 0;
price = 0.00;
}
public House(int newListingNum, double newPrice)
{
listingNum = newListingNum;
price = newPrice;
}
public int getListingNum()
{
return listingNum;
}
public double getPrice()
{
return listingNum;
}
public String toString()
{
return ("Listing number: "+listingNum+", Price: "+price);
}
public boolean sameListingNum(Object other)
{
if(!(other instanceof House))
return false;
else {
House objHouse = (House)other;
if(listingNum - objHouse.getListingNum() == 0)
{
System.out.println("Same listing numbers: "
+listingNum+", "+objHouse.getListingNum());
return true;
}
else
return false;
}
}
}
// Condo Class
public class Condo extends House
{
public int connectedUnits;
public Condo()
{
super();
connectedUnits = 0;
}
public Condo(int newListingNum, double newPrice, int newConUnits)
{
super(newListingNum, newPrice);
connectedUnits = newConUnits;
}
public double getPrice()
{
return price;
}
public int getListingNum()
{
return listingNum;
}
public int getConnectedUnits()
{
return connectedUnits;
}
public String toString()
{
return super.toString()+", Number of connected unints: "+connectedUnits;
}
public boolean sameListingNum(Object other)
{
if(!(other instanceof House))
return false;
else {
House objHouse = (House)other;
if(listingNum - objHouse.getListingNum() == 0)
{
System.out.println("Same listing numbers: "
+listingNum+", "+objHouse.getListingNum());
return true;
}
else
return false;
}
}
You can group it using a Map of List, like Map> groups.
Then you loop over you list and for each house/condo you put it in the group of the same listing number. At the end you will have a map where for each entry there are all houses/condos with same listing number.
Here a sample:
Map<Integer, List<House>> groups = new HashMap<Integer, List<House>>();
for (House house:listings) {
List<House> group = groups.get(house.getListingNum());
if (group == null) {
group = new ArrayList<House>();
groups.put(house.getListingNum(), group);
}
group.add(house);
}
for (Entry<Integer, List<House>> entry:groups.entrySet()) System.out.println("Listing Number "+entry.getKey()+" Houses/condos: "+entry.getValue());
Both of the other 2 answers will work alternativly you can implement comparable on the House... eg.
public class House implements Comparable<House>
#Override
public int compareTo(final House o) {
return listingNum - o.listingNum;
}
then inside your main method. Sort the Collection and check to see if the previous row has the same Id all the time.
Collections.sort(listings);
int previousListing = Integer.MIN_VALUE;
for (House currentHouse : listings) {
if (currentHouse.getListingNum() == previousListing){
System.out.println("Duplicate for " + currentHouse.getListingNum());
}
previousListing = currentHouse.getListingNum();
}
take your pick.
Try this:
foreach(House h in listings)
{
if(listings.Exists(p => p.sameListingNum(h)))
{
//do something
}
}

How to use CompareTo to sort the PlaneMap by Ascending and Descending order

Im trying to sort my planes by Ascending and Descending order. I have a hashmap of planes and i want to compare them so that i can get the next plane due and last plane due by sorting the map by timeLimitBeforeLand. I wrote a compareTo method which looks like :
//---------------------------------------------------------------------------------------
// CompareTo() used with the Comparable implementation.
//---------------------------------------------------------------------------------------
public int compareTo(Object arg0)
{
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.timeLimitBeforeLand - p.getLimitBeforeLand());
}
return 0;
}
CompareTo takes timeLimitBeforeLand:
// ---------------------------------------------------------------------------------------
// Name: getTimeLimitBeforeLand.
// Description: Get the time before every plane is going to land.
//---------------------------------------------------------------------------------------
public double getTimeLimitBeforeLand()
{
double fuelConsumption;
double timeLimitBeforeLand = 0;
for (TreeMap<String, Plane> theEntry : airlineMap.values()) {
for (Plane aPlane : theEntry.values()) {
if (aPlane.getPlaneType() == aPlane.getPlaneType().AIRBUS) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 2;
timeLimitBeforeLand = (double) (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
} else if (aPlane.getPlaneType() == aPlane.getPlaneType().CORPORATE) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 3;
timeLimitBeforeLand = (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
} else if (aPlane.getPlaneType() == aPlane.getPlaneType().PRIVATE) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 4;
timeLimitBeforeLand = (double) (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
}
}
}
return timeLimitBeforeLand;
}
My attempt so far in the mainApp:
TreeMap<String, PlaneStore> map = new TreeMap<String, PlaneStore>();
ArrayList<Plane> copyList = new ArrayList<Plane>(map.);
Plane comp = new Plane();
Collections.sort(copyList, plane);
Plane Class:
//---------------------------------------------------------------------------------------
// Name: Imports.
// Description: To allow the use of different Java classes.
//---------------------------------------------------------------------------------------
import java.io.Serializable;
//---------------------------------------------------------------------------------------
//Name: Class declaration.
//---------------------------------------------------------------------------------------
public class Plane implements Comparable, Serializable
{
//---------------------------------------------------------------------------------------
// Variable declarations.
//---------------------------------------------------------------------------------------
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
//---------------------------------------------------------------------------------------
// Enum declaration.
//---------------------------------------------------------------------------------------
private AIRPLANETYPE planeType;
private boolean isLanded = false;
public double timeLimitBeforeLand;
//---------------------------------------------------------------------------------------
// Enum Constuctor.
//---------------------------------------------------------------------------------------
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
//---------------------------------------------------------------------------------------
// Constructor.
//---------------------------------------------------------------------------------------
public Plane(String flightNumber, String airlineName,
double fuelRemaining, int overdue, int passengerNumber,
AIRPLANETYPE planeType, boolean isLanded)
{
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
this.isLanded = isLanded;
}
//---------------------------------------------------------------------------------------
// Getters and Setters.
//---------------------------------------------------------------------------------------
public String getAirlineName()
{
return airlineName;
}
public void setAirlineName(String airlineName)
{
this.airlineName = airlineName;
}
public void setOverdue(int overdue)
{
this.overdue = overdue;
}
public int getOverdue()
{
return overdue;
}
public String getFlightNumber()
{
return flightNumber;
}
public void setFlightNumber(String flightNumber)
{
this.flightNumber = flightNumber;
}
public double getFuelRemaining()
{
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining)
{
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber()
{
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber)
{
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType()
{
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType)
{
this.planeType = planeType;
}
public boolean isLanded()
{
return isLanded;
}
public void setLanded(boolean isLanded)
{
this.isLanded = isLanded;
}
public double getLimitBeforeLand()
{
return timeLimitBeforeLand;
}
public void setTimeLimitBeforeLand(double timeLimitBeforeLand)
{
this.timeLimitBeforeLand = timeLimitBeforeLand;
}
//---------------------------------------------------------------------------------------
// CompareTo() used with the Comparable implementation.
//---------------------------------------------------------------------------------------
public int compareTo(Object arg0)
{
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.timeLimitBeforeLand - p.getLimitBeforeLand());
}
return 0;
}
//---------------------------------------------------------------------------------------
// toString().
//---------------------------------------------------------------------------------------
public String toString()
{
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType +
"hasLanded=" + isLanded+ ".\n";
}
}
The second argument in Collections.sort is for a Comparator not a Plane. Since I saw no mention of a Comparator, you should be able to use the natural order (defined by the compareTo method in your Plane object) and not have a second argument in the Collections.sort
EDIT: Unless you have just excluded that code, you aren't creating any Plane instances and you're using empty collections here...
TreeMap<String, PlaneStore> map = new TreeMap<String, PlaneStore>();
ArrayList<Plane> copyList = new ArrayList<Plane>(map.);
and you will be sorting by PlaneStores so you have to obtain all the Planes in each PlaneStore and add them to your copyList before sorting.
I would consider researching each of the Collections a little more and deciding what the best one for your need would be.

Categories