Learning Java - function returns 0 - java

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

Related

Simple problem with method getting default valuse from class [closed]

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()).

Cant access classes through Object Java RPG character builder

Im trying to create a small character builder, using inheritance. i have CreateCharacter CharacterRace then a Dwarf class. i made a variable with type CharacterRace in CreateCharacter and a variable with type Dwarf in CharacterRace. i have an object of CreateCharacter in my main method demo and its not letting me call the methods from the Dwarf class, to make a dwarf character. im thinking ineed to pass a dwarf object in characterRace? im just not sure how. heres my code: (its a bit long my apologies)
package characterCreation;
public class CreateCharacter {
private CharacterClass characterClass;
private CharacterRace characterRace;
private Name name;
public CreateCharacter(String characterName,CharacterClass characterClass,CharacterRace characterRace) {
this.name = new Name(characterName);
this.characterClass = characterClass;
this.characterRace = characterRace;
}
public CreateCharacter(){
}
public CharacterClass getCharacterClass() {
return characterClass;
}
public void setCharacterClass(CharacterClass characterClass) {
this.characterClass = characterClass;
}
public CharacterRace getCharacterRace() {
return characterRace;
}
public void setCharacterRace(CharacterRace characterRace) {
this.characterRace = characterRace;
}
public Name getName(){
return name;
}
public void setName(Name name){
this.name = name;
}
#Override
public String toString() {
return "CreateCharacter [name=" + name + ", characterRace=" + characterRace + ", characterClass="
+ characterClass + "]";
}
}
package characterCreation;
public class CharacterRace {
protected String raceName;
protected double mana;
protected double hp;
private Dwarf dwarf;
public CharacterRace(String raceName,double mana, double hp) {
this.raceName = raceName;
this.mana = mana;
this.hp = hp;
}
public CharacterRace(){
}
public String getRaceName() {
return raceName;
}
public Dwarf getDwarf() {
return dwarf;
}
public void setDwarf(Dwarf dwarf) {
this.dwarf = dwarf;
}
public double getMana() {
return mana;
}
public double getHp() {
return hp;
}
#Override
public String toString() {
return "CharacterRace [dwarf=" + dwarf + "]";
}
}
package characterCreation;
public class Dwarf extends CharacterRace {
public Dwarf(String raceName,double mana, double hp) {
super(raceName,mana,hp);
}
public double getMana() {
mana = 5;
return mana;
}
public double getHp() {
hp = 10;
return hp;
}
public String getRaceName(){
return raceName = "Dwarf";
}
#Override
public String toString() {
return "Dwarf [mana=" + mana + ", hp=" + hp + ", getRaceName()=" + getRaceName() + "]";
}
}
package characterCreation;
import java.util.Scanner;
public class CharacterDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CreateCharacter create = new CreateCharacter();
System.out.println("Choose your Race: ");
String userRace = input.next();
create.setName(new Name("Daxel"));
//create.setCharacterRace(race);
System.out.println(create.getName());
//Dwarf dwarf = new Dwarf();
System.out.println(create.getCharacterRace().getDwarf().getRaceName());
//System.out.println(create.getCharacterRace().setDwarf(new Dwarf("dwarf",10,5)));
}
}
You have to call setCharacterRace() on create; then call setDwarf() on the characterRace; otherwise create.getCharacterRace() would be null and create.getCharacterRace().getDwarf() would throw NullPointerException.
I don't understand the logic behind your code, but try the code below:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CreateCharacter create = new CreateCharacter();
System.out.println("Choose your Race: ");
String userRace = input.next();
create.setName(new Name("Daxel"));
//***********new code starts******
CharacterRace myRace = new CharacterRace(userRace, 20, 9);
myRace.setDwarf(new Dwarf("dwarf",10,5));
create.setCharacterRace(myRace);
//***********new code ends********
//create.setCharacterRace(race);
System.out.println(create.getName());
//Dwarf dwarf = new Dwarf();
System.out.println(create.getCharacterRace().getDwarf().getRaceName());
//System.out.println(create.getCharacterRace().setDwarf(new Dwarf("dwarf",10,5)));
}

Creating an ArrayList of Employees

I have three classes
employee
production workers
shift supervisor class
My idea is to make production and shift supervisor extend the employee class and then create another class, EmployeeList to fill it with information about production workers and shift supervisors.
How can i get the names and info from employee class to iterate into an arraylist?
How can i add a random list of employees more than half being prod. workers and the rest shift supervisors?
Employee:
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Enum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C" };
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
}
ProductionWorker:
import java.util.Random;
public class ProductionWorker extends Employee {
public double HourlyRate;
public ProductionWorker()
{
super();
HourlyRate = 0;
}
public static void main(String[] args) {
ProductionWorker pw = new ProductionWorker();
Random rnd = new Random();
int count =0;
// adding random Employees.....
while(count<5)
{
int num= rnd.nextInt(Enum.length);
int decimal = rnd.nextInt(10);
double dec = decimal/10;
pw.setEmployeeName(Ename[num]);
pw.setEmployeeNumber(Enum[num]);
pw.setEmployeehireyear(rnd.nextInt(35) + 1980);
pw.setEmployeeweeklyearning(rnd.nextInt(5000) + 5000);
pw.setHourlyRate(rnd.nextInt(44) + 6 + dec);
System.out.println("EmployeeName: " + pw.getEmployeeName() + "\nEmployeeNumber: " + pw.getEmployeeNumber() +
"\nHireYear: " + pw.gethireyear() + "\nWeeklyEarning: " + pw.getWeeklyEarning() +
"\nHourlyRate: " + pw.getHourlyRate() +"\n");
count++;
}
}
public double getHourlyRate()
{
return this.HourlyRate;
}
public void setHourlyRate(double hourlyrate)
{
this.HourlyRate = hourlyrate;
}
}
ShiftSupervisor:
import java.util.Random;
public class ShiftSupervisor extends Employee{
public double YearlySalary;
public int GoalsCleared;
public ShiftSupervisor()
{
super();
YearlySalary = 0;
}
public static void main(String[] args) {
ShiftSupervisor S = new ShiftSupervisor();
Random rnd = new Random();
int count =0;
// adding random Employees.....
System.out.println("Adding Employees..");
while(count<5)
{
int num= rnd.nextInt(Enum.length);
S.setEmployeeName(Ename[num]);
S.setEmployeeNumber(Enum[num]);
S.setEmployeehireyear(rnd.nextInt(35) + 1980);
S.setEmployeeweeklyearning(rnd.nextInt(100) * 100);
S.setYearlySalary(rnd.nextInt(40000) + 40000);
System.out.println("EmployeeName:" + S.getEmployeeName() + "\nEmployeeNumber: " + S.getEmployeeNumber() +
"\nHireYear: " + S.gethireyear() + "\nWeeklyEarning: " + S.getWeeklyEarning() +
"\nearlySalary: " + S.getYearlySalary() +"\n");
count++;
}
}
// returns yearly salary
public double getYearlySalary()
{
return this.YearlySalary;
}
// returns goals cleared
public int getGoalsCleared()
{
return this.GoalsCleared;
}
// set yearly salary
public void setYearlySalary(double yearlysalary)
{
this.YearlySalary = yearlysalary;
}
}
The first thing I would do is have all necessary fields set in the constructor. If an Employee doesn't "exist" until it has a name, then that should be part of the constructor.
Then, I would suggest you consider renaming some of your fields. When I first saw Enum as a String[] and highlighted as a type, it took me a moment to figure out what exactly was going on. Renaming it to employeeNumbers could solve this.
Next, I think you should have an EmployeeGenerator class whose sole purpose is generating Employees.
public class EmployeeGenerator {
public ProductionWorker generateProductionWorker() {
Random rng = new Random();
int numberOfEmployeeNames = employeeNames.length;
String employeeName = employeeNames[rng.nextInt(numberOfEmployeeNames)];
int numberOfEmployeeNumbers = employeeNumbers.length;
String employeeNumber = employeeNumbers[rng.nextInt(numberOfEmployeeNumbers)];
ProductionWorker worker = new ProductionWorker(employeeName, employeeNumber);
int yearHired = rng.nextInt(100) + 1900;
worker.setHireYear(yearHired);
int hourlyRate = rng.nextInt(20) + 10;
worker.setHourlyRate(hourlyRate);
// any other fields...
return worker;
}
// method to generate shift supervisor
}
And then you can simply do
public static void main(String[] args) {
Random rng = new Random();
int numberOfEmployeesToGenerate = 1000;
int minimumNumberOfProductionWorkers = numberOfEmployeesToGenerate / 2;
int numberOfProductionWorkersToGenerate =
minimumNumberOfProductionWorkers + rng.nextInt(100);
int numberOfSupervisorsToGenerator =
numberOfEmployeesToGenerate - numberOfProductionWorkersToGenerate;
List<Employee> employees = new ArrayList<>();
EmployeeGenerator generator = new EmployeeGenerator();
for (int i = 0; i < numberOfProductionWorkersToGenerate; i++) {
ProductionWorker worker = generator.generateProductionWorker();
employees.add(worker);
}
for (int i = 0; i < numberOfSupervisorsToGenerate; i++) {
Supervisor supervisor = generator.generateSupervisor();
employees.add(supervisor);
}
}
This should hopefully give you a point in the right direction. This isn't perfect code, and there are other ways to refactor this to make it more maintainable and performant.
When you say you want to add a random list of employees, What do you mean exactly?
Currently you instantiate only one ProductionWorker and one ShiftSupervisor, change the values of the member variables, and print some text to StdOut.
Do you want to store instances in a list or is the console output sufficient?
Also, you have two main-methods. Which one will be performed? It might be better to have one Main class as an entry point for your application and from there create the instances.
In general you can do something like that:
public class Main {
public static void main(String[] args) {
List<Employee> emps = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//create new employee
emps.add(newEmployee);
}
//do something with list
}
}

Java inheritance issue

I am new to programming and I am having an issue with my program that should return this output:
Portfolio #00001, ASD = 42.50, DFAS = 45.00, CAC = 22.20, BDM = 52.50
Portfolio #00002, ASD = 42.50, DFAS = 45.00, CAC = 22.20, BDM = 52.50
Portfolio #00001, ASD = 43.35, DFAS = 45.90, CAC = 22.64, BDM = 53.55
Portfolio #00002, ASD = 43.35, DFAS = 45.90, CAC = 22.64, BDM = 53.55
Portfolio #00001, ASD = 41.18, DFAS = 43.61, CAC = 21.51, BDM = 50.87
Portfolio #00002, ASD = 41.18, DFAS = 43.61, CAC = 21.51, BDM = 50.87
Portfolio #00001, ASD = 43.65, DFAS = 46.22, CAC = 22.80, BDM = 53.92
Portfolio #00002, ASD = 43.65, DFAS = 46.22, CAC = 22.80, BDM = 53.92
Currently, my program is not returning anything. Could someone please help?
Here are the classes :
DisplayElement Interface :
public interface DisplayElement {
public void display();
}
Observer Interface :
public interface Observer {
public void update (Map<String,Double> priceMap);
}
You need to register your protfolios after their creation, and before calling setPrices(), as required by the observer pattern: Your program should be like :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
interface DisplayElement {
void display();
}
interface Observer {
void update (Map<String,Double> priceMap);
}
class PricesDisplay implements Observer, DisplayElement {
private String ticker;
private double price;
private Subject PriceData;
Map<String,Double> priceMap;
PricesDisplay(Subject PriceData) {
this.PriceData = PriceData;
}
PricesDisplay(String ticker, Subject PriceData) {
this.ticker = ticker;
this.PriceData = PriceData;
}
public void update(Map<String,Double> priceMap) {
this.priceMap = priceMap;
display();
}
public void display() {
for (Map.Entry<String, Double> entry : priceMap.entrySet()) {
System.out.printf("\nPortfolio #%s, " + "%s = " + "%.2f, ",
ticker, entry.getKey(), entry.getValue());
}
}
}
interface Subject{
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
void measurementsChanged();
void setPrices(Map<String,Double> priceMap);
}
class PriceData implements Subject {
private ArrayList observers;
PriceData priceData;
private Map<String,Double> priceMap = new HashMap<String,Double>();
PriceData() {
observers = new ArrayList();
}
public void registerObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObservers() {
for (int i = 0; i < observers.size(); i++) {
Observer observer = (Observer)observers.get(i);
observer.update(priceMap);
}
}
public void measurementsChanged() {
notifyObservers();
}
public void setPrices(Map<String,Double> priceMap) {
this.priceMap = priceMap;
measurementsChanged();
}
}
class Test {
private static Map<String,Double> priceMap = new HashMap<String,Double>();
private static PriceData priceData = new PriceData();
public static void main(String[] args) {
// establish two portfolios as listeners for priceData.
// for now, we assume that both portfolios contain the same
// collection of investments.
PricesDisplay firstPortfolio =
new PricesDisplay("00001", priceData);
PricesDisplay secondPortfolio =
new PricesDisplay("00002", priceData);
priceData.registerObserver(firstPortfolio);
priceData.registerObserver(secondPortfolio);
generateInitialPrices();
updatePrices(.02);
updatePrices(-.05);
updatePrices(.06);
}
static void generateInitialPrices()
{
priceMap.put("ASD", 42.50);
priceMap.put("BDM", 52.50);
priceMap.put("CAC", 22.20);
priceMap.put("DFAS", 45.00);
priceData.setPrices(priceMap);
}
static void updatePrices(double changePercent)
{
for( String key : priceMap.keySet())
{
double v = priceMap.get(key) * (1.0 + changePercent);
priceMap.put(key, v);
}
priceData.setPrices(priceMap);
}
}
setPrices should be :
public <map> void setPrices(Map<> priceMap) {
this.priceMap = priceMap; // <-- missing line
measurementsChanged();
}

Confusion on using instanceof along with other inherited data

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

Categories

Resources