This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I got to what I thought was a finished program and now java is pulling this on me.
The error I get is as follows:
Exception in thread "main" java.lang.NullPointerException
at hirecardemo.HireCar.isAvailable(HireCar.java:68)
at hirecardemo.HireCarDemo.runSimulation(HireCarDemo.java:49)
at hirecardemo.HireCarDemo.main(HireCarDemo.java:25)
Java Result: 1
Main Class:
package hirecardemo;
import java.util.Random;
public class HireCarDemo {
public static void main(String[] args) {
HireCar car0 = new HireCar("Toyota", "AV77 FGJ", 6000, 12300, 41500);
HireCar car1 = new HireCar("Mercedes", "DI99 FTZ", 6700, 7000, 91800);
HireCar car2 = new HireCar("Toyota", "FG82 FTP", 25000, 12000, 72000);
HireCar car3 = new HireCar("Vauxhall", "TW56 LTS", 10000, 11000, 19001);
HireCar car4 = new HireCar("Ford", "TD85 LTU", 13000, 12300, 12000);
HireCar car5 = new HireCar("Susuki", "GU12 UTJ", 12000, 10000, 50000);
HireCar[] fleet = {car0, car1, car2, car3, car4, car5};
int minMileage = 1000;
int maxMileage = 60000;
int numberOFevents = 12;
String [] results = HireCarDemo.runSimulation(fleet, numberOFevents,
minMileage, maxMileage);
for(int i = 0; i < numberOFevents; i++) {
System.out.println(results[i]);
}
}
/**
* #param fleet the fleet of hire cars
* #param numberOFevents the size of the events table to be generated
* #param minMileage the assumed minimum mileage driven by any hired
* car
* #param maxMileage the assumed maximum mileage driven by any hired
* car
* #return table of events generated during the simulation
*/
public static String[] runSimulation(HireCar [] fleet, int numberOFevents,
int minMileage, int maxMileage) {
int n = fleet.length; // Number of cars in the fleet.
Random carGenerator = new Random();
String [] events = new String [numberOFevents];
for(int i = 0; i < numberOFevents; i++) {
int randomNumber = carGenerator.nextInt(n-1);
if(fleet[randomNumber].isAvailable() == true)
{
fleet[randomNumber].hireOut();
events[i] = fleet[randomNumber].getRegNumber() + " <HIRE OUT>";
}
else if(fleet[randomNumber].isOnHire() == true)
{
Random mileage = new Random();
int randomMileage = mileage.nextInt(maxMileage - minMileage);
if(fleet[randomNumber].isBeingServiced() == true)
{
events[i] = fleet[randomNumber].getRegNumber() +
" <RETURN FROM HIRE>" + " <SEND FOR SERVICE>";
} else {
events[i] = fleet[randomNumber].getRegNumber() +
" <RETURN FROM HIRE>";
}
}
else
{
fleet[randomNumber].makeAvailable();
events[i] = fleet[randomNumber].getRegNumber() +
" <RETURN FROM SERVICE>";
}
}
return events;
}
}
Here is my separate class that goes along with this:
//******************************************************************************
// HireCar.java Author: Ryan Holder
//
// Represents the car hire company's fleet of cars and the information on them.
//******************************************************************************
package hirecardemo;
public class HireCar {
private String manufacturer, regNumber, carStatus;
private int mileage, serviceInterval, lastService; // All in miles.
private boolean serviceDue() {
if((mileage- lastService) >= serviceInterval) {
this.sendForService();
return true;
} else {
return false;
}
}
private void sendForService() {
carStatus = "Servicing";
}
//--------------------------------------------------------------------------
// Default Constructor: Sets information for a new car.
//--------------------------------------------------------------------------
public HireCar(String demoManufacturer, String demoRegNumber) {
manufacturer = demoManufacturer;
regNumber = demoRegNumber;
carStatus = "Available";
serviceInterval = 0;
lastService = 0;
mileage = 0;
}
public HireCar(String demoManufacturer, String demoRegNumber,
int demoMileage, int demoServiceInterval, int lastInterval) {
manufacturer = demoManufacturer;
regNumber = demoRegNumber;
mileage = demoMileage;
}
public void setMileage(int demoMileage) {
mileage = demoMileage;
}
public void setServiceInterval(int demoServiceInterval) {
serviceInterval = demoServiceInterval;
}
public void setLastService(int demoLastService) {
lastService = demoLastService;
}
public String getRegNumber() {
return regNumber;
}
public void makeAvailable() {
carStatus = "Available";
}
public boolean isAvailable() {
if(carStatus.equals("Available") || carStatus.equals("Return from Service")) {
return true;
} else {
return false;
}
}
public boolean isOnHire() {
if(carStatus.equals("On Hire")) {
return true;
} else {
return false;
}
}
public boolean isBeingServiced() {
if(carStatus.equals("Being Serviced")) {
return true;
} else {
return false;
}
}
public void hireOut() {
carStatus = "On Hire";
}
public void returnFromHire() {
if(this.serviceDue() == true) {
carStatus = "Being Serviced";
} else {
carStatus = "Available For Hire";
}
}
public void returnFromService() {
carStatus = "Return From Service";
}
public String ToString() {
return("Manufacturer: <" + this.manufacturer + ">/n "
+ "Registration Number: <" + this.regNumber + ">/n"
+ "Mileage: <" + this.mileage + ">/n"
+ "Service Interval: <" + this.serviceInterval + "</n"
+ "Last Service: <" + this.lastService + "</n"
+ "Status: <" + this.carStatus + "</n");
}
}
You are using 5-arg constructor to construct your HireCar instance: -
new HireCar("Toyota", "AV77 FGJ", 6000, 12300, 41500);
And in that constructor, you haven't set the value for - "carStatus".
public HireCar(String demoManufacturer, String demoRegNumber,
int demoMileage, int demoServiceInterval, int lastInterval) {
manufacturer = demoManufacturer;
regNumber = demoRegNumber;
mileage = demoMileage;
}
So, carStatus is still null. (You should set every field in this constructor. At least the references, because their default value is null)
So, when you invoke the isAvailable method for any of the instance you added in your array: -
fleet[randomNumber].isAvailable()
It will result in a NPE, as in isAvailable method, you are invoking equals method on carStatus: -
if(carStatus.equals("Available") || carStatus.equals("Return from Service"))
^^^
This is null here
The stacktrace is telling you that the isAvailable method is throwing a NullPointerException, so let's look at that.
public boolean isAvailable() {
if(carStatus.equals("Available") || carStatus.equals("Return from Service")) {
return true;
} else {
return false;
}
}
Unnecessary return true/false aside, the only thing here that gets dereferenced is car status, so when can it be null?
Well, look at the constructor you're using: the one with 5 arguments. At no point does it ever set the status, so it remains null. Hence the null pointer.
Use an Enum in place of String for carStatus
Initialize all the attributes in ALL constructors (the second left carStatus = null)
you are initializing carStatus in a constructor with 2-args and you never invoke that constructor, thus, carStatus is still null when you call equals() in isAvailable() method.
if(carStatus.equals("Available") || carStatus.equals("Return from Service")) {
^^^ This is **null** as it is not initialized yet, Thus **NPE**.
you should also intialize carStatus in your 5-args Constructor in-order for your current code to work.
public HireCar(String demoManufacturer, String demoRegNumber,
int demoMileage, int demoServiceInterval, int lastInterval) {
manufacturer = demoManufacturer;
regNumber = demoRegNumber;
mileage = demoMileage;
carStatus="someval" ; //initialize carStatus here
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
I started to learn java and i cant get past my problem with method getting default vaules from class. The code is about cars and garage. Everything works just as I intended with the execption of returning default values for Samochod s1 instead of the values that were set in the main function.
Main:
public static void main(String[] args) {
Samochod s1 = new Samochod("Fiat", "126p", 2, 650, 6.0);
Samochod s2 = new Samochod("Syrena", "105", 2, 800, 7.6);
Garaz g1 = new Garaz();
g1.setAdres( "ul. Garażowa 1" );
g1.setPojemnosc( 1 );
Garaz g2 = new Garaz("ul. Garażowa 2", 2);
g1.wprowadzSamochod(s1);
g1.wypiszInfo();
g1.wprowadzSamochod(s2);
g2.wprowadzSamochod(s2);
g2.wprowadzSamochod(s1);
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wyprowadzSamochod();
}
package Lab2_02;
public class Samochod {
private String marka;
private String model;
private int iloscDrzwi;
private int pojemnoscSilnika;
private double srednieSpalanie;
private static int iloscSamochodow = 0;
public String getMarka() {
return marka;
}
public String getModel() {
return model;
}
public int getIloscDrzwi() {
return iloscDrzwi;
}
public int getPojemnoscSilnika() {
return pojemnoscSilnika;
}
public double getSrednieSpalanie() {
return srednieSpalanie;
}
public void setMarka(String marka) {
this.marka = marka;
}
public void setModel(String model) {
this.model = model;
}
public void setIloscDrzwi(int iloscDrzwi) {
this.iloscDrzwi = iloscDrzwi;
}
public void setPojemnoscSilnika(int pojemnoscSilnika) {
this.pojemnoscSilnika = pojemnoscSilnika;
}
public void setSrednieSpalanie(double stednieSpalanie) {
this.srednieSpalanie = stednieSpalanie;
}
public Samochod() {
marka = "nieznany";
model = "nieznany";
iloscDrzwi = 0;
pojemnoscSilnika = 0;
srednieSpalanie = 0.0;
iloscSamochodow++;
}
public Samochod(String marka_, String model_, int iloscDrzwi_, int pojemnoscSilnika_, double srednieSpalanie_) {
marka = marka_;
model = model_;
iloscDrzwi = iloscDrzwi_;
pojemnoscSilnika = pojemnoscSilnika_;
srednieSpalanie = srednieSpalanie_;
iloscSamochodow++;
}
public double obliczSpalanie(double dlugoscTrasy) {
double spalanie = (srednieSpalanie * dlugoscTrasy)/100;
return spalanie;
}
public double obliczKosztPrzejazdu(double dlugoscTrasy, double cenaPaliwa) {
double kosztPrzejazdu = obliczSpalanie(dlugoscTrasy) * cenaPaliwa;
return kosztPrzejazdu;
}
public void wypiszInfo() {
System.out.println("Marka: " + marka);
System.out.println("Model: " + model);
System.out.println("Ilosc drzwi: " + iloscDrzwi);
System.out.println("Pojemnosc silnika: " + pojemnoscSilnika);
System.out.println("Srednie spalanie: " + srednieSpalanie);
}
public static void wypiszIloscSamochodow() {
System.out.println("Ilosc samochodow: " + iloscSamochodow);
}
}
package Lab2_02;
public class Garaz {
private String adres;
private int pojemnosc;
private int liczbaSamochodow = 0;
private Samochod [] samochody;
public String getAdres() {
return adres;
}
public int getPojemnosc() {
return pojemnosc;
}
public void setAdres(String adres) {
this.adres = adres;
}
public void setPojemnosc(int pojemnosc) {
this.pojemnosc = pojemnosc;
samochody = new Samochod[pojemnosc];
}
public Garaz() {
adres = "nieznany";
pojemnosc = 0;
samochody = null;
}
public Garaz(String adres_, int pojemnosc_) {
adres = adres_;
pojemnosc = pojemnosc_;
samochody = new Samochod[pojemnosc];
}
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod();
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
public void wyprowadzSamochod() {
if(liczbaSamochodow == 0) {
System.out.println("W garazu nie ma zadnego auta.");
}
else {
samochody [liczbaSamochodow-1] = null;
liczbaSamochodow--;
System.out.println("Samochod zostal wyprowadzony.");
}
}
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
}
}
}
So my problem is that instead of returning in console info about my car "Fiat", it say "nieznany" from default class. I know it is simple problem but i can't get past it for a few days. My problem is with this line:
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
Instead of showing this:
Samochod zostal wprowadzony.
Marka: nieznany
Model: nieznany
Ilosc drzwi: 0
Pojemnosc silnika: 0
Srednie spalanie: 0.0
I can't make it show this:
Marka: Fiat
Model: 126p
Ilosc drzwi: 2
Pojemnosc silnika: 650
Srednie spalanie: 6.0
In wprowadzSamochod(Samochod s) method you're creating a new Samochod instance, instead of using the one passed as parameter. Since you have a default constructor, you are always using it, setting information to default values:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod(); // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
How it should be:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = s; // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
Just a micro-suggestion: inside the exit condition of a for loop you can just use i < max, instead of i <= max-1 (e.g. in wypiszInfo()).
So, I have 1 superclass DessertItem. Which has 4 subclasses Candy, Cookie, Ice Cream, Sundae. The Sundae class extends the Ice Cream class. Superclass is an abstract class. I also have a separate class which does not belong to the superclass, but in the same package - Order. There is another class - DessertShop, where the main is located.
Candy, Cookie classes implement SameItem<> generic class. The generic interface SameItem<> class looks like this:
public interface SameItem<T> {
public boolean isSameAs(T other);
}
The Candy, Cookie classes have this method:
#Override
public boolean isSameAs(Candy other) {
if(this.getName() == other.getName() && this.getPricePerPound() == other.getPricePerPound()) {
return true;
}
else {
return false;
}
}
And something similar, but for the cookie class.
All the subclasses have these methods :
default constructor,
public Cookie(String n, int q, double p) {
super(n);
super.setPackaging("Box");
cookieQty = q;
pricePerDozen = p;
}
public int getCookieQty() {
return cookieQty;
}
public double getPricePerDozen() {
return pricePerDozen;
}
public void setCookieQty(int q) {
cookieQty = q;
}
public void setToppingPricePricePerDozen(double p) {
pricePerDozen = p;
}
#Override
public double calculateCost() {
double cookieCost = cookieQty * (pricePerDozen/12);
return cookieCost;
}
and toString() method
So, what my program does is gets the input from the User, asks the name of the dessert, asks the quantity, or the quantity according to the dessert, ask the unit price. Asks the payment method. And then prints the receipt. This how the Order class looks like:
import java.util.ArrayList;
import java.util.List;
public class Order extends implements Payable{
//attributes
PayType payMethod;
private ArrayList<DessertItem> OrderArray;
//Constructor
public Order() {
OrderArray = new ArrayList<>();
payMethod = PayType.CASH;
}
//methods
public ArrayList<DessertItem> getOrderList(){
return OrderArray;
}// end of getOrderList
public ArrayList<DessertItem> Add(DessertItem addDesert){
enter code here
OrderArray.add(addDesert);
/* for(DessertItem i : getOrderList()) {
if(i instanceof Candy) {
for(DessertItem j : getOrderList()) {
if(j instanceof Candy) {
if(((Candy) i).isSameAs((Candy) j)) {
*/
//this is what I have tried so far, but I am lost
}
}
}
} else if(i instanceof Cookie) {
for (DessertItem j : getOrderList()) {
if(((Cookie) i).isSameAs((Cookie)j)) {
OrderArray.add(j);
} else {
OrderArray.add(i);
}
}
}
}
return OrderArray;
}// end of Add
public int itemCount(){
int counted = OrderArray.size();
return counted;
}//end of itemCount
public double orderCost() {
double orderResult = 0;
for(int i=0; i<OrderArray.size(); i++) {
orderResult = orderResult + OrderArray.get(i).calculateCost();
}
return orderResult;
}
public double orderTax() {
double taxResult = 0;
for(int i = 0; i<OrderArray.size(); i++) {
taxResult = taxResult + OrderArray.get(i).calculateTax();
}
return taxResult;
}
public double orderTotal() {
double ordertotal = orderTax() + orderCost();
return ordertotal;
}
#Override
public PayType getType() {
// TODO Auto-generated method stub
return payMethod;
}
#Override
public void setPayType(PayType p) {
payMethod = p;
}
public String toString() {
String finalOutput = "";
finalOutput += "------------------------Receipt--------------------------\n";
for(int i = 0; i < OrderArray.size(); i++) {
finalOutput = finalOutput + OrderArray.get(i).toString();
}
finalOutput += "--------------------------------------------------\n";
String line2 = "Total Number of items in order: " + itemCount() + "\n";
String line3 = String.format("Order Subtotals:\t\t\t\t $%-6.2f", orderCost());
String line4 = String.format("[Tax: $%.2f]\n", orderTax());
String line5 = String.format("\nOrder Total:\t\t\t\t\t $%-6.2f\n", orderTotal());
String outputVar = String.format("%s\n%s%s%17s", line2, line3, line4, line5);
String ending = "----------------------------------------------------";
String payType = String.format("\nPaid for with: %s", payMethod.name());
return finalOutput + outputVar + ending + payType;
}
So, my question is, how can I combine like items into one item?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My project is to create a program which reads a number the user inputs and return relevant information corresponding to the input. I've finished my code and it compiles, but when I enter a room number it returns this error:
Exception in thread "main" java.lang.NullPointerException
at Room.setDirection(Room.java:93)
at Room.roomNumber(Room.java:29)
at Room.main(Room.java:18)
My complete program is below. I've looked at the lines corresponding to the errors but can't tell whats wrong. Any help?
import java.util.Scanner;
class artGallery
{
String direction;
String title;
String artist;
String year;
String height;
String width;
}
public class Room
{
public static void main(String[] param)
{
artGallery room;
room = roomNumber();
System.out.println("The painting " + getDirection(room) + " is called " + getTitle(room) + " and is painted by " + getArtist(room) + ". It was painted in " + getYear(room) + " and is approximately " + getHeight(room) + "cm tall and " + getWidth(room) + "cm wide.");
}
public static artGallery roomNumber()
{
int number;
Scanner scanner = new Scanner(System.in);
System.out.println("Are you in room 1, 2 ,3 or 4?");
number = scanner.nextInt();
artGallery[] room = new artGallery[5];
room[1] = setDirection(room[1], "in front of you");
room[1] = setTitle(room[1], "The Starry Night");
room[1] = setArtist(room[1], "Vincent Willem van Gogh");
room[1] = setYear(room[1], "1889");
room[1] = setHeight(room[1], "73.7");
room[1] = setWidth(room[1], "92.1");
room[2] = setDirection(room[2], "to the left of you");
room[2] = setTitle(room[2], "The Persistence of Memory");
room[2] = setArtist(room[2], "Salvador Domingo Felipe Jacinto Dalí i Domènech");
room[2] = setYear(room[2], "1931");
room[2] = setHeight(room[2], "24");
room[2] = setWidth(room[2], "33");
room[3] = setDirection(room[3], "to the right of you");
room[3] = setTitle(room[3], "Liberty Leading the People");
room[3] = setArtist(room[3], "Ferdinand Victor Eugène Delacroix");
room[3] = setYear(room[3], "1830");
room[3] = setHeight(room[3], "260");
room[3] = setWidth(room[3], "325");
room[4] = setDirection(room[4], "above you");
room[4] = setTitle(room[4], "The Creation of Adam");
room[4] = setArtist(room[4], "Michelangelo di Lodovico Buonarroti Simoni");
room[4] = setYear(room[4], "1512");
room[4] = setHeight(room[4], "280");
room[4] = setWidth(room[4], "570");
return room[number];
}
public static String getDirection(artGallery v)
{
return v.direction;
}
public static String getTitle(artGallery v)
{
return v.title;
}
public static String getArtist(artGallery v)
{
return v.artist;
}
public static String getYear(artGallery v)
{
return v.year;
}
public static String getHeight(artGallery v)
{
return v.height;
}
public static String getWidth(artGallery v)
{
return v.width;
}
public static artGallery setDirection(artGallery v, String direction)
{
v.direction = direction;
return v;
}
public static artGallery setTitle(artGallery v, String title)
{
v.title = title;
return v;
}
public static artGallery setArtist(artGallery v, String artist)
{
v.artist = artist;
return v;
}
public static artGallery setYear(artGallery v, String year)
{
v.year = year;
return v;
}
public static artGallery setHeight(artGallery v, String height)
{
v.height = height;
return v;
}
public static artGallery setWidth(artGallery v, String width)
{
v.width = width;
return v;
}
}
It means that v was not initialized before you used it.
Your artGallery objects are never created -- you only created the array of them, but not each of them individually. So they stay null all the time.
it means you are trying to access a null object,
room[1] = setDirection(room[1], "in front of you");
in your call for setDirection you are sending room[1], this is actually null, you need instead either so sent
room[1] = setDirection(new artGallery(), "in front of you");
or instantiate variable v in setDirection
This applies to all your similar methods
This question already has answers here:
required: double [] found: no arguments
(4 answers)
Closed 6 years ago.
hoping to find a solution before i put my head through my monitor.
What I am trying to do is use a boolean to make a sell function.
basically I want it not to sell stock if there is less than 0 (print error message)
if there is i want to +1 to numSold and -1 to numInStock.
when i try im getting an error
"method sellCopy in class item cannot be applied to given types; required boolean; found no arguments reason actual and formal argument list differ in length"
public abstract class Item
{
private String name;
private double price;
private int numInStock;
private int numSold;
public Item(String inName, double inPrice)
{
name = inName;
price = inPrice;
numInStock = 0;
numSold = 0;
}
public String getName()
{
return name;
}
public double getPrice()
{
return price;
}
public int getNuminStock()
{
return numInStock;
}
public int getNumSold()
{
return numSold;
}
public void receiveStock(int amount)
{
numInStock = numInStock + amount;
}
public boolean sellCopy(boolean sellCopy)
{
if (numInStock <= 0)
{
sellCopy = true;
numSold = numSold +1;
numInStock = numInStock -1;
return true;
}
else
{
sellCopy = false;
System.out.println("Stock unavalable");
return false;
}
}
}
public class Game extends Item
{
private int MaxPlayers;
public Game(String inName, int inMaxPlayers, double inPrice)
{
super(inName, inPrice);
MaxPlayers = inMaxPlayers;
}
public String toString()
{
return " Game " + super.toString() + " Maximum Player: " + MaxPlayers + "\n";
}
import java.util.*;
public class Shop
{
private ArrayList<Item> items = new ArrayList<Item>();
public boolean addItem(Item newItem)
{
if (!findItem(newItem.getName()))
{
items.add(newItem);
return true;
}
else
{
System.out.println(" Error - an item with that name " +newItem.getName() + " already exists");
return false;
}
}
public boolean findItem(String searchName)
{
for (Item nextItem : items)
{
//might be searchName//
if (searchName.equals(nextItem.getName()))
{
System.out.println(nextItem);
return true;
}
}
return false;
}
public void listItems()
{
System.out.println("The shop contains the following items***\n");
for (Item nextItem : items)
{
System.out.println(nextItem);
}
}
public void calcTotalSales()
{
double total = 0;
for (Item nextItem : items)
{
total += nextItem.getNumSold() * nextItem.getPrice();
}
System.out.println("****The total number sold is worth $" + total);
System.out.println("****");
}
}
public class test
{
public static void main (String args[])
{
//create the shop
Shop myShop = new Shop();
//create a Game and add it to the shop
Game game1 = new Game("Chess", 2, 39.95);
myShop.addItem(game1);
//order and get stock
game1.receiveStock(5);
//sell some items
game1.sellCopy();
//the bastard right here//
//print information about shop
myShop.calcTotalSales();
//test error conditions
Game game2 = new Game("Chess", 2, 39.95);
myShop.addItem(game2); //should fail as a Chess item is already in the shop
//eg2.sellCopy();
}
}
If you look at the code,
game1.sellCopy();
That sellCopy method needs a boolean. You need to pass it.
game1.sellCopy(true);// for example. Pass your actual value.
I have already made a posting about this program once, but I am once again stuck on a new concept that I am learning (Also as a side note; I am a CS student so please DO NOT simply hand me a solution, for my University has strict code copying rules, thank you.). There are a couple of difficulties I am having with this concept, the main one being that I am having a hard time implementing it to my purposes, despite the textbook examples making perfect sense. So just a quick explanation of what I'm doing:
I have an entity class that takes a Scanner from a driver. My other class then hands off the scanner to a superclass and its two subclasses then inherit that scanner. Each class has different data from the .txt the Scanner read through. Then those three classes send off their data to the entity to do final calculations. And that is where my problem lies, after all the data has been read. I have a method that displays a new output along with a few methods that add data from the super along with its derived classes.EDIT: I simply cannot figure out how to call the instance variable of my subclasses through the super so I can add and calculate the data.
Here are my four classes in the order; Driver, Entity, Super, Subs:
public static final String INPUT_FILE = "baseballTeam.txt";
public static void main(String[] args) {
BaseballTeam team = new BaseballTeam();
Scanner inFile = null;
try {
inFile = new Scanner(new File(INPUT_FILE));
team.loadTeam(inFile);
team.outputTeam();
} catch (FileNotFoundException e) {
System.out.println("File " + INPUT_FILE + " Not Found.");
System.exit(1);
}
}
}
public class BaseballTeam {
private String name;
private Player[] roster = new Player[25];
Player pitcher = new Pitcher();
Player batter = new Batter();
BaseballTeam() {
name = "";
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public void loadTeam(Scanner input) {
name = input.nextLine();
for (int i = 0; i < roster.length; i++) {
if (i <= 9) {
roster[i] = new Pitcher();
}
else if ((i > 9) && (i <= 19)) {
roster[i] = new Batter();
}
else if (i > 19) {
roster[i] = new Player();
}
roster[i].loadData(input);
roster[i].generateDisplayString();
//System.out.println(roster[i].generateDisplayString()); //used sout to test for correct data
}
}
public void outputTeam() {
if ((pitcher instanceof Player) && (batter instanceof Player)) {
for (int i = 0; i < roster.length; i++) {
System.out.println(roster[i].generateDisplayString());
}
}
//How do I go about doing calculates?
public int calculateTeamWins() {
if ((pitcher instanceof ) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamSaves() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamERA() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamWHIP() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamBattingAverage() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamHomeRuns() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamRBI() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateStolenBases() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
}
public class Player {
protected String name;
protected String position;
Player(){
name = "";
position = "";
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public String getPosition() {
return position;
}
public void setPosition(String aPosition) {
position = aPosition;
}
public void loadData(Scanner input){
do {
name = input.nextLine();
} while (name.equals(""));
position = input.next();
//System.out.println(generateDisplayString());
}
public String generateDisplayString(){
return "Name: " + name + ", Position:" + position;
}
}
public class Pitcher extends Player {
private int wins;
private int saves;
private int inningsPitched;
private int earnedRuns;
private int hits;
private int walks;
private double ERA;
private double WHIP;
Pitcher() {
super();
wins = 0;
saves = 0;
inningsPitched = 0;
earnedRuns = 0;
hits = 0;
walks = 0;
}
public int getWins() {
return wins;
}
public void setWins(int aWins) {
wins = aWins;
}
public int getSaves() {
return saves;
}
public void setSaves(int aSaves) {
saves = aSaves;
}
public int getInningsPitched() {
return inningsPitched;
}
public void setInningsPitched(int aInningsPitched) {
inningsPitched = aInningsPitched;
}
public int getEarnedRuns() {
return earnedRuns;
}
public void setEarnedRuns(int aEarnedRuns) {
earnedRuns = aEarnedRuns;
}
public int getHits() {
return hits;
}
public void setHits(int aHits) {
hits = aHits;
}
public int getWalks() {
return walks;
}
public void setWalks(int aWalks) {
walks = aWalks;
}
#Override
public void loadData(Scanner input) {
super.loadData(input);
wins = input.nextInt();
saves = input.nextInt();
inningsPitched = input.nextInt();
earnedRuns = input.nextInt();
hits = input.nextInt();
walks = input.nextInt();
}
#Override
public String generateDisplayString() {
calculateERA();
calculateWHIP();
return String.format(super.generateDisplayString() + ", Wins:%1d, Saves:%1d,"
+ " ERA:%1.2f, WHIP:%1.3f ", wins, saves, ERA, WHIP);
}
public double calculateERA() {
try {
ERA = ((double)(earnedRuns * 9) / inningsPitched);
} catch (ArithmeticException e) {
ERA = 0;
}
return ERA;
}
public double calculateWHIP() {
try {
WHIP = ((double)(walks + hits) / inningsPitched);
} catch (ArithmeticException e) {
WHIP = 0;
}
return WHIP;
}
}
public class Batter extends Player {
private int atBats;
private int hits;
private int homeRuns;
private int rbi;
private int stolenBases;
private double batAvg;
Batter() {
super();
atBats = 0;
hits = 0;
homeRuns = 0;
rbi = 0;
stolenBases = 0;
}
public int getAtBats() {
return atBats;
}
public void setAtBats(int aAtBats) {
atBats = aAtBats;
}
public int getHits() {
return hits;
}
public void setHits(int aHits) {
hits = aHits;
}
public int getHomeRuns() {
return homeRuns;
}
public void setHomeRuns(int aHomeRuns) {
homeRuns = aHomeRuns;
}
public int getRbi() {
return rbi;
}
public void setRbi(int aRbi) {
rbi = aRbi;
}
public int getStolenBases() {
return stolenBases;
}
public void setStolenBases(int aStolenBases) {
stolenBases = aStolenBases;
}
#Override
public void loadData(Scanner input) {
super.loadData(input);
atBats = input.nextInt();
hits = input.nextInt();
homeRuns = input.nextInt();
rbi = input.nextInt();
stolenBases = input.nextInt();
}
#Override
public String generateDisplayString() {
calculateBattingAverage();
return String.format(super.generateDisplayString() +
", Batting Average:%1.3f, Home Runs:%1d, RBI:%1d, Stolen Bases:%1d"
, batAvg, homeRuns, rbi, stolenBases);
}
public double calculateBattingAverage() {
try{
batAvg = ((double)hits/atBats);
} catch (ArithmeticException e){
batAvg = 0;
}
return batAvg;
}
}
Also, its probably easy to tell I'm still fairly new here, because I just ran all my classes together in with the code sample and I can't figure out to add the gaps, so feel free to edit if need be.
The typical usage of instanceof in the type of scenario you're describing would be
if (foo instanceof FooSubclass) {
FooSubclass fooSub = (FooSubclass) foo;
//foo and fooSub now are references to the same object, and you can use fooSub to call methods on the subclass
} else if (foo instanceof OtherSubclass) {
OtherSubclass otherSub = (OtherSubclass) foo;
//you can now use otherSub to call subclass-specific methods on foo
}
This is called "casting" or "explicitly casting" foo to FooSubclass.
the concept to call the methods of your subclasses is called polymorphism.
In your runtime the most specific available method is called provided that the method names are the same.
so you can
Superclass class = new Subclass();
class.method();
and the method provided that overwrites the method in Superclass will be called, even if it's defined in the Subclass.
Sorry for my english, I hope that helps a little bit ;-)