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()).
Related
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?
I know this must be a fundamental design problem because I clearly can't do this. I want to call the ownGrokk, ownTyce, etc methods from another class depending on the value of the integer assigned to OwnedSpirits(int). This in turn fills arrays.
The problem is, I do this multiple times, and doing it from another class it seems like I have to make a new object every time to pass the new int argument, and doing so resets the value of spiritInstance. And, since that resets to zero, the arrays don't fill properly. I try to print out my array values later and I get an "ArrayIndexOutOfBoundsException".
public class OwnedSpirits {
private int spiritTypeInt = 0;
public static int spiritInstance=0;
public static int[] spiritarray = new int[9];
public static String[] spiritName = new String[9];
public static int[] party = new int[3];
public OwnedSpirits(int spiritcall){
if(spiritcall == 1){
ownGrokk();
}
if(spiritcall == 2){
ownRisp();
}
if(spiritcall == 3){
ownTyce();
}
if(spiritcall == 4){
ownDaem();
}
if(spiritcall == 5){
ownCeleste();
}
}
private void ownGrokk(){
spiritName[spiritInstance] = "Grokk";
spiritInstance++;
}
private void ownRisp(){
spiritName[spiritInstance] = "Risp";
spiritInstance++;
}
private void ownDaem(){
spiritName[spiritInstance] = "Daem";
spiritInstance++;
}
private void ownCeleste(){
spiritName[spiritInstance] = "Celeste";
spiritInstance++;
}
private void ownTyce(){
spiritName[spiritInstance] = "Tyce";
spiritInstance++;
}
and this code is in another class, where it attempts to call the methods to fill the array
buttonConfirm.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
if(xcounter==3){
for(x=0; x<3; x++){
if(setdaemtrue == true){
new OwnedSpirits(4);
}
if(setrisptrue == true){
new OwnedSpirits(2);
}
if(setcelestetrue == true){
new OwnedSpirits(5);
}
if(settycetrue == true){
new OwnedSpirits(3);
}
if(setgrokktrue == true){
new OwnedSpirits(1);
}
}
}
}
});
and finally in yet another class:
System.arraycopy(OwnedSpirits.spiritName, 0, partylist, 0, 3);
#Override
public void show() {
System.out.println(partylist[0]);
System.out.println(partylist[1]);
System.out.println(partylist[2]);
spiritlist.setItems(partylist);
table.add(spiritlist);
table.setFillParent(true);
stage.addActor(table);
}
If the last part is confusing, it's because I am using libgdx. the print statements are there just to try to figure out why my list was having an error
I can show you what I would do to handle Spirits, and Parties.
The Spirit class, contains name and current party its assigned to:
package com.stackoverflow.spirit;
public class Spirit {
private String name;
private Party party;
private SpiritType type;
private static int id = 0;
public static enum SpiritType {
Grokk, Risp, Tyce, Daem, Celeste
};
public Spirit(String name, SpiritType type) {
create(name, type);
}
public Spirit(SpiritType type) {
create(null, type);
}
// This is to handle Java inexistance of default parameter values.
private void create(String name, SpiritType type)
{
Spirit.id++;
this.name = (name == null) ? (type.name() + " " + id) : name;
this.type = type;
}
public String getName() {
return name;
}
public Party getParty() {
return party;
}
public SpiritType getType() {
return type;
}
/**
* Used internally by #see Party
* #param party the party this Spirit belongs
*/
public void setParty(Party party) {
this.party = party;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString()
{
return this.name;
}
}
Finally the Party class, contains a set of Spirits, you can add and remove Spirits from the party.
package com.stackoverflow.spirit;
import java.util.HashSet;
public class Party {
private HashSet<Spirit> spirits = new HashSet<Spirit>();
private static int id = 0;
private String name = "Party " + Party.id++;;
public Party() {
}
public Party(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(Spirit spirit) {
if (!spirits.contains(spirit)) {
spirits.add(spirit);
if (spirit.getParty() != null) {
//Remove from previous party to update the other party set
spirit.getParty().remove(spirit);
}
spirit.setParty(this);
} else {
// throw new SpiritAlreadyOnParty();
}
}
public void remove(Spirit spirit)
{
if (spirits.contains(spirit))
{
spirit.setParty(null); // You could create a default empty party for "Nature/Neutral" Spirits perhaps :)
spirits.remove(spirit);
}
else {
//throw new SpiritNotInParty();
}
}
public boolean isOnParty(Spirit spirit) {
return spirits.contains(spirit);
}
public ArrayList<Spirit> getSpirits()
{
return new ArrayList<Spirit>(spirits);
}
public int getPartySize() {
return spirits.size();
}
public String getPartyInfo()
{
StringBuilder builder = new StringBuilder();
builder.append("Party:" + this.name + " Size:" + this.spirits.size() + "\n");
for (Spirit s : spirits)
{
builder.append(s.getName() + "\n");
}
return builder.toString();
}
#Override
public String toString()
{
return this.name;
}
}
Here I use the Spirit and Party classes, you could add more functionality, like properties for party strength, magic buffs on the party, etc:
package com.stackoverflow.spirit;
import com.stackoverflow.spirit.Spirit.SpiritType;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Party griffindor = new Party("Griffindor"), slytherin = new Party(
"Slytherin");
// You can also do for (SpiritType type : SpiritType.values() then
// type.ordinal()
for (int i = 0; i < SpiritType.values().length; i++) {
griffindor.add(new Spirit(SpiritType.values()[i]));
slytherin.add(new Spirit(SpiritType.values()[i]));
}
Spirit mySpirit = new Spirit("NotAHPFan", SpiritType.Celeste);
slytherin.add(mySpirit);
System.out.println("Name of party:" + mySpirit.getParty().getName());
System.out.println("Is on griffindor?:"
+ griffindor.isOnParty(mySpirit));
// What now?
griffindor.add(mySpirit);
System.out.println("Is " + mySpirit.getName() + " on "
+ slytherin.getName() + "?:" + slytherin.isOnParty(mySpirit));
System.out.println(mySpirit.getName() + " is now on "
+ mySpirit.getParty() + "\n");
System.out.println(griffindor.getPartyInfo());
System.out.println(slytherin.getPartyInfo());
}
}
P.D: I'm not a HP fan.
I'm just learning Java... I have three classes which creates bank account
My first class;
public class Banka {
protected static int pocetUctu = 0;
public Ucet vytvorUcet(Clovek maj, double pocatecni) {
Ucet uc = new Ucet(maj, pocatecni);
pocetUctu++;
System.out.println("Ucet " + uc + " vytvoren");
System.out.println("Pocet uctu " + pocetUctu);
return uc;
}
public static void main(String[] args) {
Banka b1 = new Banka();
Clovek pn = new Clovek("Petr Novotny", 1949);
Clovek jv = new Clovek("Jan Vesely", 1970);
Ucet pu1 = b1.vytvorUcet(pn, 1000);
Ucet pu2 = b1.vytvorUcet(pn, 50000);
Ucet ju = b1.vytvorUcet(jv, 3000);
pu2.prevedNa(ju, 1000);
ju.prevedNa(pu1, 500);
pu1.vypisInfo();
pu2.vypisInfo();
ju.vypisInfo();
}
}
My second class;
public class Clovek {
protected String jmeno;
protected int rokNarozeni;
protected static int pocetLidi = 0;
public Clovek(String j, int rN) {
jmeno = j;
rokNarozeni = rN;
pocetLidi++;
}
public void vypisInfo() {
System.out.println("Clovek:");
System.out.println("Jmeno="+jmeno);
System.out.println("Rok narozeni="+rokNarozeni);
}
}
My third class;
public class Ucet {
static double zustatek;
static Clovek majitel;
public Ucet(Clovek maj, double zus) {
maj = majitel;
zus = zustatek;
}
public void pridej(double pocatecni) {
zustatek += pocatecni;
}
public void vypisZustatek() {
System.out.println(zustatek);
}
public Ucet prevedNa(Ucet kam, float castka) {
zustatek -= castka; // nebo také vhodné je: pridej(-castka);
kam.pridej(castka);
return this;
}
public void vypisInfo() {
System.out.println("Vlastník" + majitel);
System.out.println("Zůstatek" + zustatek);
}
}
pu1.vypisInfo(); should output account owner and his money on it, but It shows owner null and balance 0. Where can be problem ?
Assignment is from right to left
majitel = maj;
zustatek = zus;
You have:
public Ucet(Clovek maj, double zus) {
maj = majitel;
zus = zustatek;
}
But you should have:
public Ucet(Clovek maj, double zus) {
majitel = maj;
zustatek = zus;
}
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 ;-)
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
}