I have this code below: If I call my object statement like this I get this.
Output below:
trafficqueue.TrafficQueue$Car#1b26af3
trafficqueue.TrafficQueue$Car#8b819f
public class TrafficQueue {
private Car[] carArray;
private int numberOfcarsInQueue;
private int f = 0;
public TrafficQueue(int numberOfcarsInQueue){
carArray = new Car[numberOfcarsInQueue];
}
private static class Car {
private String make;
private String colour;
public Car(String make, String colour) {
this.make = make;
this.colour = colour;
}
public String getMake(){
return make;
}
} ;
public void add(Car car){
carArray[numberOfcarsInQueue] = car;
numberOfcarsInQueue ++;
}
public String toString()
{
String result = "";
for (int scan=0; scan < numberOfcarsInQueue; scan++)
result = result + carArray[scan].toString() + "\n";
return result;
}
public static void main(String[] args) {
// TODO code application logic here
TrafficQueue queueLane1 = new TrafficQueue(10);
Car carT = new Car("Toyota", "Red");
Car carE = new Car ("Jaguar","Red");
queueLane1.add(carT);
queueLane1.add(carE);
System.out.println(""+queueLane1.toString());
System.out.println(queueLane1);
System.out.println("Number of Cars in Queue"+ "=" + queueLane1.getNumberOfCarsInQueue());
}
}
I have tried using the java.util.arrays.toString but to no avail. What am I doing wrong?
The output that you're getting is produced by calling toString on the TrafficQueue object i.e. this method:
public String toString() {
String result = "";
for (int scan = 0; scan < numberOfcarsInQueue; scan++)
result = result + carArray[scan].toString() + "\n";
return result;
}
Let's examine the above method.
The above method calls carArray[scan].toString(). carArray[scan] is an instance of Car. What you're doing here is essentially calling toString on a Car.
Did you define a toString method for Car? Nope. That's why the default toString is called. That's why you see outputs like this
trafficqueue.TrafficQueue$Car#1b26af3
If you want a human readable string representation of Car, just override toString:
public String toString() {
return colour + " " + getMake();
}
Your whole Car class should look like this:
private static class Car {
private String make;
private String colour;
public Car(String make, String colour) {
this.make = make;
this.colour = colour;
}
public String getMake() {
return make;
}
#Override
public String toString() {
return colour + " " + getMake();
}
}
Related
I'm having a goofy issue. I'm trying to see if I can printout the restaurants and employees data I have here and I can't remember how best to do it this.
Once I can figure out how to do that, I'll be able to create methods using it, but I can't seem to remember how to do it this way.
Updated Code
class Main {
public static void main(String[] args) {
Employee john = new Employee("John","asian",35.00);
Employee sam = new Employee("Sam","Greek",25.00);
Employee michael = new Employee("Michael","Italian",50.00);
Restaurant asian = new Restaurant("Asian","asian",25.00);
Restaurant greek = new Restaurant("greek","greek",25.00);
Restaurant italian = new Restaurant("italian","italian",25.00);
}
public static class Restaurant {
private String restaurantName;
private String cuisine;
private double price;
public Restaurant( String restaurantName,
String cuisine,
double price) {
this.restaurantName = restaurantName;
this.cuisine = cuisine;
this.price = price;
}
public String getRestaurantName() {
return restaurantName;
}
public String getCuisine() {
return cuisine;
}
public double getPrice() {
return price;
}
}
public static class Employee {
private String employeeName;
private String cuisine;
private double budget;
public Employee(String employeeName,
String cuisine,
double budget) {
this.employeeName = employeeName;
this.cuisine = cuisine;
this.budget = budget;
}
public String getEmployeeName() {
return employeeName;
}
public String getCuisine() {
return cuisine;
}
public double getBudget() {
return budget;
}
}
}
For printing out the data of an object you can override the toString method.
After that, the class Restaurant looks like this.
public static class Restaurant {
private String restaurantName;
private String cuisine;
private double price;
public Restaurant( String restaurantName,
String cuisine,
double price) {
this.restaurantName = restaurantName;
this.cuisine = cuisine;
this.price = price;
}
public String getRestaurantName() {
return restaurantName;
}
public String getCuisine() {
return cuisine;
}
public double getPrice() {
return price;
}
#Override
public String toString() {
return "Restaurant [restaurantName=" + restaurantName + ", cuisine=" + cuisine + ", price=" + price + "]";
}
}
the class Employee looks like this.
public static class Employee {
private String employeeName;
private String cuisine;
private double budget;
public Employee(String employeeName,
String cuisine,
double budget) {
this.employeeName = employeeName;
this.cuisine = cuisine;
this.budget = budget;
}
public String getEmployeeName() {
return employeeName;
}
public String getCuisine() {
return cuisine;
}
public double getBudget() {
return budget;
}
#Override
public String toString() {
return "Employee [employeeName=" + employeeName + ", cuisine=" + cuisine + ", budget=" + budget + "]";
}
}
and then you can print an object in sysout
System.out.println(michael);
You have to use a toString method() for each Object's class.
For example in Employee Class:
public String toString()
{
String str = "Employee Name: " + employeeName +
"\nCuisine: " + cuisine + "\nBudget: " + budget;
return str;
}
After that you just have to use the toString() in the main() method:
System.out.println(john.toString());
In the main method you could also use an array to store the data and make it easier to access. Then to display both of the objects inside you could use just one for loop, but I used two to keep the outputs separate from one another.
int numEmployees = 3;
Employee myEmployees[] = new Employee[numEmployees];
myEmployees[0] = new Employee("John","asian",35.00); // Stores John in index 0...
myEmployees[1] = new Employee("Sam","Greek",25.00);
myEmployees[2] = new Employee("Michael","Italian",50.00);
// Displays each object who's index is associated with the value for i
for(int i = 0; i < employees.length; i++)
System.out.println(myEmployees[i].toString());
int numRestaurants = 3;
Restaurant myRestaurants = new Restaurant[numRestaurant]
myRestaurants[0] = new Restaurant("Asian","asian",25.00); // Stores Asain in index 0...
myRestaurants[1] = new Restaurant("greek","greek",25.00);
myRestaurants[2] = new Restaurant("italian","italian",25.00);
// Displays each object who's index is associated with the value for i
for(int i = 0; i < restaurants.length; i++)
System.out.println(myRestaurants[i].toString());
I have this constructor class here
public class Car {
private String make,model;
private int year,mileage;
public String toString() {
return "Car [make=" + make + ", model=" + model +", "
+ "year =" + year + ", mileage=" + mileage + "]"; }
public String getMake() {
return make;
}
public Car(String make, String model, int year, int mileage) {
super();
this.make = make;
this.model = model;
this.year = year;
this.mileage = mileage;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
}
Now using this I'm trying to store the data into two arrays where one will be sorted using the sorting algorithm but I'm having trouble understanding how i'm supposed to store them in arrays when they're different types. I attempted to try it on my own but I think i'm not doing it right. It's supposed to read from a text file and store the make, model year and mileage but the fact that it's two data types is throwing me off.
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Storing {
public static void main(String[] args) {
TextFileInput fileInput = new TextFileInput("CarDetails.txt");
ArrayList <Car> cars = new ArrayList<Car>();
String line = fileInput.readLine();
while(line!=null) {
int [] values = new int [4];
StringTokenizer st = new StringTokenizer(line,",");
int numOfCommas = st.countTokens();
for(int i = 0;i<numOfCommas;i++) {
values[i]=Integer.parseInt(st.nextToken(","));
}
cars.add(new Car(values[0],values[1],values[2],values[3]));
line = fileInput.readLine();
}
Please help me get in the right direction.
make and model aren't int(s). Just read in a String[] and only parse the last two tokens. Something like,
while (line != null) {
String[] values = new String[4];
StringTokenizer st = new StringTokenizer(line, ",");
int numOfCommas = st.countTokens();
for (int i = 0; i < numOfCommas; i++) {
values[i] = st.nextToken();
}
cars.add(new Car(values[0], values[1],
Integer.parseInt(values[2]), Integer.parseInt(values[3])));
line = fileInput.readLine();
}
You could possibly parse it into a different data type and back. Generics will allow for a single data type at a time but not 2 different data types at the same time...
I'm made a program that creates an invoice but when it comes numbers in the thousands the output isn't neat and ruins everything. How do I fix this so the program's columns are more aligned with numbers like this? Here is the code I used to create the program. If anyone could help, it would be much appericated.
Here's the one with the main method...
public class InvoicePrinter
{
public static void main(String[] args)
{
Address samsAddress=new Address("Sam's Small Appliances", "100 Main
Street", "Anytown", "CA", "98765");
Invoice samsInvoice =new Invoice(samsAddress);
samsInvoice.add(new Product("Toaster", 29.95),3);
samsInvoice.add(new Product("Hair Dryer", 24.95),1);
samsInvoice.add(new Product("Car Vacuum",19.99),2);
samsInvoice.add(new Product("Nano Parts",100000),1);
samsInvoice.addSimple(new Product("Shipping",5.00));
System.out.println(samsInvoice.format());
}
}
These are the other programs needed for the program to work
import java.util.ArrayList;
public class Invoice
{
public Invoice(Address anAddress)
{
items=new ArrayList<LineItem>();
billingAddress=anAddress;
simpleItems= new ArrayList<SimpleLineItem>();
}
public void addSimple(Product aProduct)
{
SimpleLineItem anItem= new SimpleLineItem(aProduct);
simpleItems.add(anItem);
}
public void add(Product aProduct, int quantity)
{
LineItem anItem=new LineItem(aProduct,quantity);
items.add(anItem);
}
public String format()
{
String r=" I N V O I C E\n\n"+billingAddress.format()+String.format("\n\n%-30s%8s%5s%8s\n","Description", "Price","Qty","Total");
for(LineItem i:items)
{
r=r+i.format()+"\n";
}
for(SimpleLineItem j:simpleItems)
{
r=r+j.format() + "\n";
}
r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
return r;
}
public double getAmountDue()
{
double amountDue = 0;
for (LineItem i : items)
{
amountDue = amountDue + i.getTotalPrice();
}
for(SimpleLineItem j:simpleItems)
{
amountDue = amountDue + j.getPrice();
}
return amountDue;
}
private Address billingAddress;
private ArrayList<LineItem> items;
private ArrayList<SimpleLineItem> simpleItems;
}
Few more
public class LineItem
{
public LineItem(Product aProduct, int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}
public double getTotalPrice()
{
return theProduct.getPrice() *quantity;
}
public String format()
{
return String.format("%'-30s%'8.2f%'5d%'8.2f", theProduct.getDescription(),theProduct.getPrice(),quantity,getTotalPrice());
}
private int quantity;
private Product theProduct;
}
Another one
public class SimpleLineItem
{
public SimpleLineItem(Product aProduct)
{
theProduct=aProduct;
}
public double getPrice()
{
return theProduct.getPrice();
}
public String format()
{
return String.format("%-30s" +" " + "%8.2f",
theProduct.getDescription(), theProduct.getPrice());
}
private Product theProduct;
}
Two more
public class Product
{
public Product(String aDescription,double aPrice)
{
description = aDescription;
price = aPrice;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
private String description;
private double price;
}
Last one
public class Address
{
public Address(String aName, String aStreet, String aCity, String
aState,String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
public String format()
{
return name + "\n" + street + "\n" + city + ", " + state + " " + zip;
}
private String name;
private String street;
private String city;
private String state;
private String zip;
}
Maybe you can take a look at the javadocs by Oracle on System.out.format and DecimalFormat class
Formatting Numeric Print Output
So basically this happens when you cannot decide the total length of your number column until you print out everything. For this you will need to set the number column's length to the lengthiest number or in your case price length and justify right all the numbers. So you'll need to add all the numbers to an array and loop through them to find the lengthiest number.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have looked on here and spent some time on this and now I have hit a brick wall.
I am wokring on the Parking Ticket simulator in Java.
I am not very good at Java, but seem to have most of it working.
The only problem is that I put in a demo/test file and it gives me the same answer all the time. Even with ridiculous values.
Can someone point me in the right direction on how to resolve this?
Thanks, All the code is below:
/**
* #(#)ParkedCar.java
*
* ParkedCar application
*
*
* #version 3.00 2014/2/9
*/
public class ParkedCar
{
//Define Variables
private String CarMake;
private String CarModel;
private String CarColour;
private String CarLicensePlate;
private static int NumberOfMinutesParked;
//Define Constructors
// NO ARGUMENT CONSTRUCTOR
// Set Vaules to Zero or null
public ParkedCar()
{
CarMake = " ";
CarModel = " ";
CarColour = " ";
CarLicensePlate = " ";
NumberOfMinutesParked = 0;
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkedCar(String Make,String Model,String Colour,String Reg, int NoMinsPkd)
{
CarMake = Make;
CarModel = Model;
CarColour = Colour;
CarLicensePlate = Reg;
NumberOfMinutesParked = NoMinsPkd;
}
// Use the SET Method
// Set the variables - no needed
public void setMake(String Make)
{
CarMake = Make;
}
public void setModel(String Model)
{
CarModel = Model;
}
public void setColour(String Colour)
{
CarColour = Colour;
}
public void setReg(String Reg)
{
CarLicensePlate = Reg;
}
public void setNoMinsPkd(int NoMinsPkd)
{
NumberOfMinutesParked = NoMinsPkd;
}
// USE THE GET METHODS
// Get the Variables - used to read in values
public String getMake()
{
return CarMake;
}
public String getModel()
{
return CarModel;
}
public String getColour()
{
return CarColour;
}
public String getReg()
{
return CarLicensePlate;
}
public static int getNoMinsPkd()
{
return NumberOfMinutesParked;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String PkdCar = "Make: " + CarMake
+ "\nModel: " + CarModel
+ "\nColor: " + CarColour
+ "\nLicense Plate: " + CarLicensePlate;
return PkdCar;
}
}
Then
/**
* #(#)ParkingMeter.java
*
* ParkedCar application
*
*
* #version 4.00 2014/2/9
*/
public class ParkingMeter
{
//Define Variables
private static int MinsPurchsed;
//Define Constructors
// NO ARGUMENT CONSTRUCTOR
// Set Vaules to Zero or null
public ParkingMeter()
{
// MinsPurchsed = 0;
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkingMeter(int Purchased)
{
MinsPurchsed = Purchased;
}
// Use the SET Method
// Set the variables - not needed
public void setPurchased(int Purchased)
{
MinsPurchsed = Purchased;
}
// USE THE GET METHODS
// Get the Variables
public static int getPurchased()
{
return MinsPurchsed;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String MeterString = "Minutes Purchased: " + MinsPurchsed;
return MeterString;
}
}
Then
/**
* #(#)GardaOfficer.java
*
* ParkedCar application
*
*
* #version 3.00 2014/2/9
* #version 4.50 2014/4/13
*/
public class GardaOfficer //extends ParkedCar
{
// Define all the variables
//==========================
private String Name;
private String BadgeNumber;
private double Ticket;
// Constructor to accept all the variables
//========================================
public GardaOfficer(String n, String num)
{
Name = n;
BadgeNumber = num;
}
// NO ARGUMENT CONSTRUCTOR
//========================
public GardaOfficer()
{
Name = "";
BadgeNumber = "";
}
// SET METHODS
//===============
public void setName(String n)
{
Name = n;
}
public void setBadgeNumber(String num)
{
BadgeNumber = num;
}
// GET METHODS
//===============
public String getName()
{
return Name;
}
public String getBadgeNumber()
{
return BadgeNumber;
}
// TO STRING METHOD
//=================
public String toString()
{
String GardaString = "Garda : " + this.Name
+ "\nBadge: " + BadgeNumber
+ "\nTicket: " + Ticket;
return GardaString;
}
public ParkingTicket search(ParkedCar car, ParkingMeter meter)
{
GardaOfficer Garda = new GardaOfficer(this.Name,this.BadgeNumber);
int time = ParkedCar.getNoMinsPkd() - ParkingMeter.getPurchased();
if(ParkedCar.getNoMinsPkd() > ParkingMeter.getPurchased())
{
if(time <= 60)
{
Ticket = 50;
}
else
{
Ticket = 50 + (10 * (time/60));
}
}
if(time <0)
return null;
return new ParkingTicket(car, Garda, getTicket(), time);
}
public double getTicket()
{
return Ticket;
}
public void setTicket(double ticket)
{
this.Ticket = Ticket;
}
}
Then
/**
* #(#)ParkingTicket.java
*
* ParkedCar application
*
*
* #version 4.00 2014/2/9
*/
public class ParkingTicket
{
//Define Variables
private ParkedCar Vehicle;
private GardaOfficer GuardString;
private double ParkingFine;
private int Minutes;
private double firstFine = 50;
private double moreFine = 50;
public ParkingTicket()
{
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkingTicket(ParkedCar car, GardaOfficer Guard, double guyFine, int mins)
{
Vehicle = car;
GuardString = Guard;
ParkingFine = guyFine;
Minutes = mins;
}
// Use the SET Method
// Set the variables - not needed
// USE THE GET METHODS
// Get the Variables
public void getTotalFine()
{
int time = ParkedCar.getNoMinsPkd() - ParkingMeter.getPurchased();
if (time <= 60)
{
ParkingFine = firstFine;
}
else
{
ParkingFine = firstFine + moreFine * (time / 60);
}
}
public double getFirstFine()
{
return firstFine;
}
public double getMoreFine()
{
return moreFine;
}
public ParkedCar getVehicle()
{
return Vehicle;
}
public GardaOfficer getGuardString()
{
return GuardString;
}
public int getMinutes()
{
return Minutes;
}
public double getFine()
{
return ParkingFine;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String TicketString = "Fine : " + this.ParkingFine
+ "\nMinutes: " + Minutes
+ "\n" + Vehicle.toString()
+ "\n" + this.getGuardString().toString();
return TicketString;
}
}
Finally
//This is a demo file to show the program
public class DemoCar
{
public static void main(String[] args)
{
ParkedCar Test1 = new ParkedCar("BMW", "2014", "Yellow", "141D12345", 30);
ParkingMeter parking = new ParkingMeter(50);
GardaOfficer Murphy = new GardaOfficer("Guard Murphy", "10");
ParkingTicket ticket = Murphy.search(Test1, parking);
if (ticket != null)
{
System.out.println(ticket.toString());
}
else
{
System.out.println("No ticket issued!");
}
// A second car checked to see if it passes or not, it's over
ParkedCar Test2 = new ParkedCar("VW", "2001", "Green", "01D321", 225);
ParkingMeter parking2 = new ParkingMeter(200);
ParkingTicket ticket2 = Murphy.search(Test2, parking2);
if (ticket != null)
{
System.out.println(ticket.toString());
}
else
{
System.out.println("No ticket issued!");
}
}
}
You're printing ticket instead of ticket2 the second time around.
Also you should always make your variables lowercase.
public class ParkedCar {
private String make;
private String model;
private String color;
private String licenseNum;
public ParkedCar(String make, String model, String color, String licenseNum) {
this.make = make;
this.model = model;
this.color = color;
this.licenseNum = licenseNum;
}
public void setMake(String ma) {
make = ma;
}
public void setModel(String mo) {
model = mo;
}
public void setColor(String c) {
color = c;
}
public void setLicenseNum(String ln) {
licenseNum = ln;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
public String getLicenseNum() {
return licenseNum;
}
}
public class ParkingMeter {
private ParkedCar parkedcar;
private int timePurchased;
private int timeParked;
public ParkingMeter(ParkedCar parkedcar, int timePurchased, int timeParked) {
this.parkedcar = parkedcar;
this.timePurchased = timePurchased;
this.timeParked = timeParked;
}
/*public ParkingMeter (ParkedCar parkedcar) {
this.parkedcar = null;
}*/
public void setTimePurchased(int timePurchased) {
this.timePurchased = timePurchased;
}
public int getTimePurchased() {
return timePurchased;
}
public void setTimeParked(int timeParked) {
this.timeParked = timeParked;
}
public int getTimeParked() {
return timeParked;
}
public int TimeExpired() {
if (timeParked > timePurchased)
return timeParked - timePurchased;
else
return 0;
}
public String toString() {
return "Make: " + parkedcar.getMake() + "\nModel: " + parkedcar.getModel() + "\nColor: " + parkedcar.getColor() + "\nLicense Number: " + parkedcar.getLicenseNum();
}
}
public class ParkingTicket {
private ParkingMeter parkingmeter;
public ParkingTicket(ParkingMeter parkingmeter) {
this.parkingmeter = parkingmeter;
}
public int TicketCost() {
if (parkingmeter.getTimeParked() > parkingmeter.getTimePurchased()) {
if (parkingmeter.getTimeParked() <= 60)
return 25;
else
return 25 + (10*(parkingmeter.TimeExpired())/60);
}
else
return 0;
}
}
public class PoliceOfficer {
private String OfficerName;
private int OfficerNum;
private ParkingMeter pm;
private ParkingTicket pt;
public PoliceOfficer(ParkingTicket pt, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
public void setOfficerName(String OfficerName) {
this.OfficerName = OfficerName;
}
public void setOfficerNum(int OfficerNum) {
this.OfficerNum = OfficerNum;
}
public String getOfficerName() {
return OfficerName;
}
public int getOfficerNum() {
return OfficerNum;
}
public boolean isExpired() {
if (pm.getTimeParked() > pm.getTimePurchased())
return true;
else
return false;
}
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
}
public class ParkingTicketDemo {
public static void main(String[] args) {
ParkedCar pc = new ParkedCar("Toyota", "Camry", "Blue", "BXZ 152");
System.out.println(pc);
ParkingMeter pm = new ParkingMeter(pc, 60, 120);
ParkingTicket pt = new ParkingTicket(pm);
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
}
}
I have been trying to create a program to create and issue a parking ticket and have run into the problem where it compiles, but when it runs it gives out the error message Exception in thread "main" java.lang.NullPointerException. I am a fairly new programmer and this is the first time I have encountered the problem so I have yet fully understand it and cannot seem to fix it. i have tried reading other things online, but just do not understand I would love a simple explaination to my problem.
The NPE happens because of these two lines:
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
In your constructor for PoliceOfficer, you don't do anything with the ParkingTicket instance pt.
public PoliceOfficer(ParkingTicket pt /* not set anywhere */, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
The fields ParkingMeter pm and ParkingTicket pt remain null since you haven't initialized them.
Then you try to print the object: System.out.println(po); What this does is call toString() on po, it is equivalent to this:
System.out.println(po.toString());
Now because your toString()
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
uses the pt, it creates a NullPointerException, since pt is null.
Since you are already passing a ParkingTicket instance into the constructor for PoliceOfficer, use that instance to assign its member variable pt.