java - ArrayList not expanding when adding objects through a loop -
i think there might multiple things wrong want add ship every time loop runs through again in diver class. reason tostring method outputs latest 1 added or last iteration of while loop. can post code if necessary assume problem in 1 of these 2 classes.
ship class
import java.util.scanner; public class shipdriver { static ship cs; static ship cargo; public static void main(string[] args) { system.out.println("----------------------ship company----------------------"); string name, ans; int year, passenger = 0, ton = 0, onetwo; scanner kb = new scanner(system.in); shipcompany sh = new shipcompany(); { system.out.println("enter ship's name:"); name = kb.next(); system.out.println("enter " + name + " build year:"); year = kb.nextint(); system.out.println("enter 1 cruise ship or 2 cargo ship"); onetwo = kb.nextint(); if(onetwo == 1) { system.out.println("enter number of passengers " + name); passenger = kb.nextint(); } else { system.out.println("enter maximum capacity of " + name); ton = kb.nextint(); } cs = new cruiseship(name, year, passenger); cargo = new cargoship(name, year, ton); sh.add(getinfo(onetwo)); system.out.println("do want enter ship's information? y/n"); ans = kb.next(); }while(ans.equals("y") || ans.equals("y") || ans.equals("yes") || ans.equals("yes") ); system.out.println(sh.tostring()); kb.close(); } public static ship getinfo(int num) { if(num == 1) { return cs; } else return cargo; } } shipcompany class
import java.util.arraylist; public class shipcompany { static arraylist<ship> arr; ship ship = new cargoship(); ship ship2 = new cruiseship(); public shipcompany() { arr = new arraylist<ship>(); } public static void add(ship o) { arr.add(o); } public string tostring() { for(int = 0; < arr.size(); i++) { if(shipdriver.getinfo() instanceof cargoship) { return ship.tostring(); } else return ship2.tostring(); } } } if need other 3 classes can post them said, i'm pretty sure problem might tostring method or add method. i'm not sure how fix it. appreciated.
when call constructor of cruiseship or cargoship call super class constructor old value of static filed arr lost.
Comments
Post a Comment