Issue printing array list constructed of defined classes - java

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();
}
}

Related

Why Can't I Get The Data I Want From This Enum?

I need to know:
Why can't I pass maxSpeed to method as an int rather than Integer?
Why does it work using "getMaxSpeed.equals(speed)" method but can't compare less than/greater than? (I think because of maxSpeed being Integer rather than int, right?). The code doesn't compile with compareTo.
I need to get a list of all cars with maxSpeed greater than 'speed', how do I do this?
How can I return not only the name(BMW, Mercedes) but also the engineCc?
Tried using both normal operators for primitives and methods for objects.
enum CarData {
BMW (230, 3000),
Mercedes (220, 2500);
private int maxSpeed;
private int engineCc;
CarData (int maxSpeed, int engineCc) {
this.maxSpeed = maxSpeed;
this.engineCc = engineCc;
}
Integer getMaxSpeed(){
return maxSpeed;
}
int getEngineCc() {
return engineCc;
}
public static CarData getByMaxSpeed (int speed) {
for (CarData carData : CarData.values()){
if (carData.getMaxSpeed() => speed)
return carData;
}
return null;
}
}
public class VehicleInfo {
public static void main (String [] args){
System.out.println (CarData.getByMaxSpeed(200));
}
}
Expected result is "BMW, Mercedes" or "3000, 2500", whichever one I need.
int is a primitive data type in Java.
Integer is a wrapper class. You can't compare instances of a wrapper class (like Integer) in the same way you do with primitives, with Integer you have to use methods, with primitives it is simpler.
For the output try overriding the toString method in your enum, this toString method is inherited from the Object class.
The complete class would be
enum CarData {
BMW(230, 3000),
Mercedes(220, 2500);
private int maxSpeed;
private int engineCc;
/* This method was added/overwritten */
#Override
public String toString() {
return name() + ", Cc: " + engineCc;
}
CarData(int maxSpeed, int engineCc) {
this.maxSpeed = maxSpeed;
this.engineCc = engineCc;
}
Integer getMaxSpeed() {
return maxSpeed;
}
int getEngineCc() {
return engineCc;
}
public static CarData getByMaxSpeed(int speed) {
for (CarData carData : CarData.values()) {
//Here I replaced the => by >=
if (carData.getMaxSpeed() >= speed) {
return carData;
}
}
return null;
}
}
public class VehicleInfo {
public static void main(String[] args) {
System.out.println(CarData.getByMaxSpeed(200));
}
}
}
And the output:
BMW, Cc: 3000
If you want a different string just customize the return in the toString method, also you have to replace the => by >= to make the comparison.
Hope this helps.

How can I show all objects on 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();

Creating Objects of a Class in Java that declares an array of object, but only one of them will print

The goal of my program is to store data for students(First Name, Last Name, ID#).I'm trying to create 4 Arrays. One array will hold the combined value of each student object that I'm adding(myDB). The other 3 hold indexes to the original spot of each value(Fname,Lname,ID) and add them to an ordered array without sorting the array. The trouble I'm having is that once I add something to the Index Arrays and go to print them, it prints all of the IDs regardless of what object I call.
//class containing methods to list, add, and delete
//Class that declares the main database array that holds all three (ID,First,Last)
import java.io.FileInputStream;
import java.util.*;
public class DataBase
{
private String tempID, tempFname, tempLname;
private DataBaseArray myDB;
private int nextDBRecord;
private IndexArray ID;
private IndexArray First;
private IndexArray Last;
public DataBase()
{
nextDBRecord = 0;
myDB =new DataBaseArray(100);
ID=(new IndexArray(100));
First=new IndexArray(100);
Last=new IndexArray(100);
}
void addData(String last, String first, String id)
{
tempLname = new String(last);
tempFname = new String(first);
tempID = new String(id);
//ID.insert(new IndexRecord(tempID, nextDBRecord));
First.insert(new IndexRecord(tempFname,nextDBRecord));
Last.insert(new IndexRecord(tempLname,nextDBRecord));
//Adds to main DB with
myDB.getStudentArray()[nextDBRecord]= (new DataBaseRecord(tempLname,tempFname,tempID));
System.out.println(myDB.getStudentArray()[nextDBRecord]);
nextDBRecord++;
}
void addIt ()
{
Scanner keyb = new Scanner(System.in);
System.out.println("Please enter the ID for new student entry");
tempID=keyb.next();
ID.insert(new IndexRecord(tempID, nextDBRecord));
System.out.println("Please enter the first name of the new student");
tempFname=keyb.next();
First.insert(new IndexRecord(tempFname, nextDBRecord));
System.out.println("Please eneter the last name of the new student");
tempLname=keyb.next();
Last.insert(new IndexRecord(tempLname,nextDBRecord));
//Adds to main DB with
myDB.getStudentArray()[nextDBRecord]= (new DataBaseRecord(tempLname,tempFname,tempID));;
nextDBRecord++;
}
void findIt()
{
}
void list (int type, int order)
{
First.printIt(order);
}
}
//Class that creates the objects to add to Iarray Farray Iarray
//IndexArray is a static array
//Creates a single entry into the IndexArray
//Need a compareTo method that gives the where value of each object
public class IndexRecord
{
private String key; //Value
private int where; //Where it is at in DataBaseArray
IndexRecord (String value, int position)
{
setKey(new String(value));
where = position;
}
public String toString()
{
return getKey()+" "+ String.valueOf(where);
}
public String getKey() //Getter for key value of the new student that is being added
{
return key;
}
public void setKey(String key) //Setter for key value of the new student that is being added
{
this.key = key;
}
}
//Same as OrderedArray Class
//Add Iterator methods. Instead of printing here, tell DataBase class what DatabaseRecord objects to print
public class IndexArray
{
private static IndexRecord[] irArray;
private int nOfElem; //Should be the same for each array so only 1 counter is needed
private int maxSize;
private int theIterator;
public IndexArray(int size)
{
nOfElem = 0;
maxSize=size;
irArray = new IndexRecord[size];
}
//-----------------------------Getters and Setters-------------------------------------
public int size() //Getter to find num of elements in array that can be called in other class
{ return nOfElem; }
public IndexRecord[] getIRarray()
{
return irArray;
}
//---------------------Iterator Methods-----------------------------------------------------
void iteratorToFront()
{
theIterator=(nOfElem>0? 0 : -1);
}
void iteratorToBack()
{
theIterator=(nOfElem>0 ? nOfElem-1 : -1);
}
boolean hasNext()
{
return (theIterator==nOfElem-1? false:true );
}
boolean hasPrevious()
{
return (theIterator==0? false : true);
}
public IndexRecord getIterator()
{
return(theIterator==-1 ? null :irArray[theIterator]);
}
int getNext()
{
theIterator=(hasNext()? theIterator+1: -1);
return(theIterator==-1? null : theIterator);
}
int getPrevious()
{
theIterator=(hasPrevious()? theIterator-1:-1);
return (theIterator==-1? null : theIterator);
}
//------------------Methods Called In Main---------------------------------------
public boolean insert(IndexRecord ir)
{
if(maxSize==nOfElem) return false;
int j;
for(j=nOfElem-1;j>=0;j--)
{
if(irArray[j].getKey().compareToIgnoreCase(ir.getKey())<0)break;
{
irArray[j+1]=irArray[j]; //Pushes all objects down to make room for new one
}
}
irArray[j+1]=ir;
nOfElem++;
return true;
}
public int find(String searchKey)
{
int lowerBound = 0;
int upperBound = nOfElem-1;
int currentRef;
while(true)
{
currentRef = (lowerBound + upperBound) / 2;
String tempValue = String.valueOf(irArray[currentRef].getKey());
if(tempValue.compareTo(searchKey) == 0)
return currentRef;
else if (lowerBound > upperBound)
return nOfElem; //returns a pointer to an empty slot
else
{
if(tempValue.compareTo(searchKey) > 0)
lowerBound = currentRef++;
else
upperBound = currentRef - 1;
}
}
}
//delete
public void printIt(int order)
{
switch(order)
{
case -1:
iteratorToBack();
break;
case 1:
iteratorToFront();
while(hasNext())
{
System.out.println(irArray[getNext()]);
}
break;
default:
}
}
}

Overriding value in heap java programming

I've added to my project a new data structure Heap<Integer,Integer> but the only problem I've got is that it prints me only one time the result.
If I have the input:
v=10;new(v,20);new(a,22);print(v)
at the end of execution
Heap={1->20, 2->22},
SymTable={v->1, a->2}
But what it gives me:
Heap: 1->22
SymTable: a -> 1
v -> 1
It overrides the first value.Here is the code from the controller where is the main part:
HeapAllocation crtStmt1=(HeapAllocation) crtStmt;
String varI = crtStmt1.getVarname();
Exp e = crtStmt1.getExpression();
int i=0;
Id<Object,Integer> tbl = state.getDict();
IHeap<Integer,Integer> heap1 = state.getHeap();
int value= e.eval(tbl, heap1);
heap1.put(++i, value);
if (tbl.containsKey(varI))
tbl.update(varI,i);
tbl.update(varI, i);
The problem I guess is after this line:
heap1.put(++i, value);
because for a new operation it doesn't append to the previous one, just overrides it.
Edit:
The implementation of the heap:
public class Heap<Integer,In> implements IHeap<Integer, Integer>,Serializable{
private Map<Integer, Integer> mapp;
public Heap(){
mapp = new HashMap<Integer,Integer>();
}
public void put(Integer index, Integer value){
mapp.put(index, value);
}
public void remove(Integer index){
try{
if(isEmpty())
throw new ExceptionRepo();
else
mapp.remove(index);
}catch (ExceptionRepo ex){
System.err.println("Error: Heap is empty.");
}
}
public boolean isEmpty(){
return mapp.isEmpty();
}
public Integer get(Integer index){
return mapp.get(index);
}
public boolean containsIndex(Integer index){
return mapp.containsKey(index);
}
public void update(Integer index, Integer value){
mapp.put(index, value);
}
public String toString(){
Set<Integer> all = mapp.keySet();
Object[] keysA= all.toArray();
String res="";
for(int i=0; i<mapp.size(); i++){
Integer v = mapp.get(keysA[i]);
res += keysA[i].toString() + "->" + v.toString() + "\r\n";
}
return res;
}
}
Edit2: Maybe the problem is in the eval function implementation.To be clear, I have a Exp class:
public class Exp{
public int eval(Id<Object,Integer> tbl)throws ExceptionRepo{
return 0;
}
public String toString(){
return "";
}
public int eval(Id<Object,Integer> tbl,IHeap<Integer,Integer> heap) throws ExceptionRepo{
return 0;
}
And some derived classes that extends the Exp class.I added a new method in the ConstExp class:
public class ConstExp extends Exp implements Serializable{
int number;
public int eval(Id<Object,Integer> tbl) throws ExceptionRepo{
return number;
}
public ConstExp(int n){
number = n;
}
public String toString(){
return "" + number;
}
public int eval(Id<Object,Integer> tbl,IHeap<Integer,Integer> heap) throws ExceptionRepo{
return number; //THIS IS THE NEW METHOD
}
This class should return a value..so for "v=20", after execution of the statement it puts the value 20 in the v based on this class implementation.
If it's useful this is the statement evaluation rule for the heap(that I implemented in the controller up there):
Stack1={new(var,exp)| Stmt2|...}
SymTable1
Heap1
==>
Stack2={Stmt2|...}
let be v=eval(exp,SymTable1,Heap1) in
Heap2 = Heap1 U {newfreelocation ->v}
if var exists in SymTable1 then SymTable2 = update(SymTable1,
var,newfreelocation)
else SymTable2 = add(SymTable1,var, newfreelocation)
How to resolve this?

Calling a method of a class without creating object of it

class A{
String z(){
System.out.println("a");
return "sauarbh";
}
}
class B{
A a;
A x(){
return a;
}
}
public class runner {
public static void main(String[] args) {
B b = new B();
A a2=b.x();
a2.z(); // Calling A class method without creating object of it
}
}
another example
class Person
{
private String lastName;
private String firstName;
private int age;
//--------------------------------------------------------------
public Person(String last, String first, int a)
{ // constructor
lastName = last;
firstName = first;
age = a;
}
//--------------------------------------------------------------
public void displayPerson()
{
System.out.print(" Last name: " + lastName);
System.out.print(", First name: " + firstName);
System.out.println(", Age: " + age);
}
//--------------------------------------------------------------
public String getLast() // get last name
{ return lastName; }
} // end class Person
////////////////////////////////////////////////////////////////
class ClassDataArray
{
private Person[] a; // reference to array
private int nElems; // number of data items
public ClassDataArray(int max) // constructor
{
a = new Person[max]; // create the array
nElems = 0; // no items yet
}
//--------------------------------------------------------------
public Person find(String searchName)
{ // find specified value
int j;
for(j=0; j<nElems; j++) // for each element,
if( a[j].getLast().equals(searchName) ) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return a[j]; // no, found it
} // end find()
//-------------------------------------------------------------- // put person into array
public void insert(String last, String first, int age)
{
a[nElems] = new Person(last, first, age);
nElems++; // increment size
}
//--------------------------------------------------------------
public boolean delete(String searchName)
{ // delete person from array
int j;
for(j=0; j<nElems; j++) // look for it
if( a[j].getLast().equals(searchName) )
break;
if(j==nElems) // can't find it
return false;
else // found it
{
for(int k=j; k<nElems; k++) // shift down
a[k] = a[k+1];
nElems--; // decrement size
return true;
}
} // end delete()
//--------------------------------------------------------------
public void displayA() // displays array contents
{
for(int j=0; j<nElems; j++) // for each element,
a[j].displayPerson(); // display it
}
//--------------------------------------------------------------
} // end class ClassDataArray
////////////////////////////////////////////////////////////////
class ClassDataApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ClassDataArray arr; // reference to array
arr = new ClassDataArray(maxSize); // create the array
// insert 10 items
arr.insert("Evans", "Patty", 24);
arr.insert("Smith", "Lorraine", 37);
arr.insert("Yee", "Tom", 43);
arr.insert("Adams", "Henry", 63);
arr.insert("Hashimoto", "Sato", 21);
arr.insert("Stimson", "Henry", 29);
arr.insert("Velasquez", "Jose", 72);
arr.insert("Lamarque", "Henry", 54);
arr.insert("Vang", "Minh", 22);
arr.insert("Creswell", "Lucinda", 18);
arr.displayA(); // display items
String searchKey = "Stimson"; // search for item
Person found;
found=arr.find(searchKey);
if(found != null)
{
System.out.print("Found ");
found.displayPerson();
}
else
System.out.println("Can't find " + searchKey);
System.out.println("Deleting Smith, Yee, and Creswell");
arr.delete("Smith"); // delete 3 items
arr.delete("Yee");
arr.delete("Creswell");
arr.displayA(); // display items again
} // end main()
} // end class ClassDataApp
As in above code i am calling z() method of class A with reference a2 without creating object of class A,As i am new to java i want to know which concept is this in java in the shown code ? for now i just know that if we want to call a method without creating object of it we have to make that method as static .
in the second example using person reference found we are able to call displayPerson() method without null pointer exception
To call:
String z(){
System.out.println("a");
return "sauarbh";
}
without the object of the class A the method z has to be static:
static String z(){
System.out.println("a");
return "sauarbh";
}
So change your code as following:
class A{
static String z(){
System.out.println("a");
return "sauarbh";
}
}
class B{
A a;
A x(){
return a;
}
}
public class runner {
public static void main(String[] args) {
B b = new B();
b.x();
A.z();
}
}
Output :
a
Yes without instantiate the class if you want to call the method you should use static key word.
What are you doing here?
You are indirectly try to get instance of A. But this case you will get NullPointerException since you just return only a reference(variable) of A
B b = new B();
A a2=b.x();
a2.z(); // NullPointerException from here
NPE?
class B{
A a;
A x(){
return a; // you just return the reference
// it should be return new A();
}
}
For your edit:
Take a look at insert() method. It is creating Person instance.
Class B method x() is not returning new object of A. Instead you are returning object of Class A with null value.
A a; // value of a is null
A x() {
return a;
}
In runner class
A a2=b.x(); // b.x() will return a, which is null. so A a2=null
a2.z(); // Equivalent to null.z() throws NullPointerException
Make below changes in your Class B code:
class B{
A a;
A x(){
return new A();// return new object of Class A;
}
}
or
class B{
A a= new A(); // Initialize Class A with new object
A x(){
return a;
}
}

Categories