I'm very stuck trying to solve an excercise consisting of a java pack being tested with some tests I find impossible to pass.
There are two classes in the pack, namely Car and Parking. The relationship between them is an aggregation - Parking is the compound and Car is the component:
Parking -parking (0...1)<>------- -cars(*) Car
-parking and -cars are the attributes which with the classes Parking and Car are respectively related. The attribute -parking can have two values, 0 or 1, and -cars is an array of undefined dimension.
A car can be assigned to one or none parkings. Likewise, a parking is compound of a variable number of parking lots.
The code is as follows:
package package;
public class Parking {
private String name; // Parking's name
private String address; // Parking's address
private int capacity; // Parking's capacity (number of cars can be parked in)
private Car[] cars; // Array of cars that can be parked
public Parking() { // Default constructor
name = "Default parking";
address = "59th Street";
capacity = 10;
cars = new Car[capacity];
}
public Car[] getCars() { // Getter of the array 'cars'
return cars;
}
public int getFirstFreeParkingLot() { // Returns first free empty slot of the
// array 'cars'. A car can be parked there.
// Otherwise, returns -1
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] == null) {
b = true;
break;
}
}
if (!b) return -1;
else return i;
}
public void addCar (Car car) throws Exception { // Adds a car to a parking lot
if (car == null) throw new Exception("[ERROR] The car cannot be null");
else if (getParkingLotNumberByCar(car) != -1) throw new Exception("[ERROR] This car is already in this parking");
else if (isFull()) throw new Exception("[ERROR] This parking is full");
else if (getFirstFreeParkingLot() != -1) {
cars[getFirstFreeParkingLot()] = car;
car.setParking(car.getParking());
}
}
public void removeCar (Car car) throws Exception { // remove a car from a parking
// lot
if(getParkingLotNumberByCar(car) != -1) {
cars[getParkingLotNumberByCar(car)] = null;
car.setParking(null);
}
else throw new Exception("[ERROR] This car does not exist in this parking");
}
public boolean isFull() { // Checks if the parking is full.
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] == null) {
b = true;
break;
}
}
return !b;
}
public boolean isFree() { // Checks if there's at least one empty parking lot
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] == null) {
b = true;
break;
}
}
return b;
}
public boolean isEmpty() { // Checks if the entire parking lot is empty
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] != null) {
b = true;
break;
}
}
return !b;
}
public int getParkingLotNumberByCar (Car car) { // Return the index of the array
// 'cars' where the car given as
// argument is present in the
// parking lot. Otherwise, returns -1
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] == car) {
b = true;
break;
}
}
if (!b) return -1;
else return i;
}
public int getNumFreeParkingLots() { // Return the number of free parking lots in a parking
int i;
int n = 0;
for (i = 0; i < cars.length; i++) {
if (cars[i] == null) n++;
}
return n;
}
}
package package;
import javax.management.ObjectName;
import java.time.LocalDate;
import java.util.Objects;
import java.util.UUID;
public class Car {
private Parking parking;
public Car() {
parking = null;
}
public Parking getParking() {
return parking;
}
public void setParking(Parking parking) throws Exception {
if (parking == null)
this.parking = null;
else {
parking.addCar(parking.getCars()[parking.getParkingLotNumberByCar(new Car())]);
if (this.parking != parking) this.parking.removeCar(parking.getCars()[parking.getParkingLotNumberByCar(new Car())]);
}
}
}
And here's one test which I don't pass as an example:
package package;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import static org.junit.jupiter.api.Assertions.*;
#TestInstance(Lifecycle.PER_CLASS)
#TestMethodOrder(OrderAnnotation.class)
class IntegrationTest {
Parking parking1;
Car car1;
#BeforeAll
void init(){
try {
parking1 = new Parking();
car1 = new Car();
} catch (Exception e) {
e.printStackTrace();
fail("Init failed");
}
}
#Test
#Order(1)
void testIntegration1() {
try {
parking1.addCar(car1);
assertEquals(0, parking1.getParkingLotNumberByCar(car1));
assertEquals(9, parking1.getNumFreeParkingLots());
assertEquals(1, parking1.getFirstFreeParkingLot());
assertEquals(car1, parking1.getCars()[parking1.getParkingLotNumberByCar(car1)]);
assertEquals(parking1, car1.getParking());
} catch (Exception e) {
e.printStackTrace();
fail("Integration1 failed");
}
}
The critical part comes when utilizing the setParking (Parking parking) method in the Car class and the addCar (Car car) and removeCar (Car car) methods in the Parking class. The setParking method in the Car class establishes the attribute parking and also calls the methods addCar and remove Car of the Parking class, which in turn add to and remove a car from a parking, and finally call the mentioned setParking method.
I get to add a Car to a parking, but I fail in adding the parking's information to that car.
To refer to a Car object in the Car class, I use 'new Car', and when it comes to the Parking class, I use 'new Parking'. Am I proceeding correctly?
All the tests I'm failing at are related with the unsuccessful intertwining of these above-mentioned methods - parking.addCar, parking.removeCar, car.setParking.
Could somebody help me?
Thank you a lot in advance
I finally found a solution.
public class Parking {
private String name; // Parking's name
private String address; // Parking's address
private int capacity; // Parking's capacity (number of cars can be parked in)
private Car[] cars; // Array of cars that can be parked
public Parking() { // Default constructor
name = "Default parking";
address = "59th Street";
capacity = 10;
cars = new Car[capacity];
}
public Car[] getCars() { // Getter of the array 'cars'
return cars;
}
public int getFirstFreeParkingLot() { // Returns first free empty slot of the
// array 'cars'. A car can be parked there.
// Otherwise, returns -1
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] == null) {
b = true;
break;
}
}
if (!b) return -1;
else return i;
}
public void addCar (Car car) throws Exception {
if (car == null) throw new Exception("[ERROR] The car cannot be null");
else if ((getParkingLotNumberByCar(car) != -1)) throw new Exception("[ERROR] This car is already in this parking");
else if (isFull()) throw new Exception("[ERROR] This parking is full");
else if (isFree()) {
cars[getFirstFreeParkingLot()] = car;
car.setParking(this);
}
}
public void removeCar (Car car) throws Exception {
if(getParkingLotNumberByCar(car) != -1) {
cars[getParkingLotNumberByCar(car)] = null;
car.setParking(null);
}
else throw new Exception("[ERROR] This car does not exist in this parking");
}
public boolean isFull() { // Checks if the parking is full.
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] == null) {
b = true;
break;
}
}
return !b;
}
public boolean isFree() { // Checks if there's at least one empty parking lot
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] == null) {
b = true;
break;
}
}
return b;
}
public boolean isEmpty() { // Checks if the entire parking lot is empty
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] != null) {
b = true;
break;
}
}
return !b;
}
public int getParkingLotNumberByCar (Car car) { // Return the index of the array
// 'cars' where the car given as
// argument is present in the
// parking lot. Otherwise, returns -1
int i;
boolean b = false;
for (i = 0; i < cars.length; i++) {
if (cars[i] == car) {
b = true;
break;
}
}
if (!b) return -1;
else return i;
}
public int getNumFreeParkingLots() { // Return the number of free parking lots in a parking
int i;
int n = 0;
for (i = 0; i < cars.length; i++) {
if (cars[i] == null) n++;
}
return n;
}
}
public class Car {
private Parking parking;
public Car() {
parking = null;
}
public Parking getParking() {
return parking;
}
public void setParking(Parking parking) throws Exception {
if (parking != null) {
if (parking.getParkingLotNumberByCar(this) == -1) {
parking.addCar(this);
}
if (this.parking != null && this.parking != parking) {
this.parking.removeCar(this);
}
this.parking = parking;
}
else {
if (this.parking != null) {
if (this.parking.getParkingLotNumberByCar(this) != -1)
this.parking.removeCar(this);
}
this.parking = null;
}
}
}
I've topped with a problem I can not understand exactly what's happening here.
I operate with a TreeMap<Custom_class, TreeMap<Custom_class, Integer>>
Here is the fragment of code:
TreeMap<Coordenada, Integer> helper_tree;
boolean newLine = false;
for (Linea l : this.lineas) {
int helper = 0;
newLine = true;
Coordenada helper_co = null;
for (Coordenada c : l.getNodosLinea()) {
helper++;
if (!c.getEsEstacion() && !c.getEsCruce()) continue;
if (newLine) { map.putIfAbsent(c, new TreeMap<>()); helper_co = c; helper = 0; newLine = false; continue; }
helper_tree = new TreeMap<>();
helper_tree.put(helper_co, helper * 200);
map.put(c, helper_tree);
map.get(helper_co).put(c, helper * 200);
helper_co = c;
helper = 0;
}
}
In the execution the highlighted line fails, getting 0 entry for a key:
debug mode in intellij
And this is TreeMap structure:
TreeMap structure
I dont understand why in fails at .get(key) when the key Coordenada(12,2) is present. All before works just fine.
Coordenada class
public class Coordenada implements Comparable<Coordenada>{
private int[] coordenada = new int[2];
private boolean esEstacion = false;
private boolean esCruce = false;
public Coordenada(int[] coordenada){
this.coordenada[0] = coordenada[0];
this.coordenada[1] = coordenada[1];
}
public void setCoordenada(int[] coordenada) {
this.coordenada = coordenada;
}
public int[] getCoordenada() {
return coordenada;
}
public void switchEstacion(){
this.esEstacion = !this.esEstacion;
}
public void switchCruce() { this.esCruce = !this.esCruce; }
public boolean getEsEstacion() {
return this.esEstacion;
}
public boolean getEsCruce() { return this.esCruce; }
#Override
public boolean equals(Object coord){
Coordenada coordTemp = (Coordenada) coord;
if (this.coordenada[0] != coordTemp.coordenada[0])
return false;
if (this.coordenada[1] != coordTemp.coordenada[1])
return false;
return true;
}
#Override
public int compareTo(Coordenada o) {
if (this.coordenada[0] > o.coordenada[0] )
return 1;
if (this.coordenada[1] > o.coordenada[1] )
return 1;
if (this.coordenada[0] < o.coordenada[0])
return -1;
if (this.coordenada[1] < o.coordenada[1])
return -1;
return 0;
}
#Override
public String toString() {
return "(" + coordenada[0] + ", " + coordenada[1] + ")";
}
}
Inserts perfectly Coordenada(12,2) and modifies previous helper_co = Coordenada(10,2)
debugger variables
Thanks for any help!
Look at your compareTo function
(0,1) compareTo (1,0) returns 1
(1,0) compareTo (0,1) returns 1
It's ambiguous.
The goal is to pass a data structure(queue) through a constructor and return a new queue once it goes through a method. I created a method of type Queue that converts from infix to postfix order. The problem is, when I pass the queue through the constructor, I am outputting all 'a's instead of the equation itself. So, I know that the linked list is passing the LENGTH of the queue, but not the characters themselves.
Output:
a+b+c/(d+f)
aaaaaaaaaaa
Main Class:
import java.io.*;
import java.lang.*;
class Convert
{
static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
public static QueueADT infixToPostFix(QueueADT in)
{
QueueADT infix = in;
QueueADT result = new QueueADT();
StackADT stack = new StackADT();
while(infix.empty() == false)
{
char c = infix.dequeue();
if (Character.isLetterOrDigit(c))
result.enqueue(c);
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.empty() && stack.peek() != '(')
result.enqueue(stack.pop());
stack.pop();
}
else // an operator is encountered
{
while (!stack.empty() && Prec(c) <= Prec(stack.peek()))
result.enqueue(stack.pop());
stack.push(c);
}
}
// pop all the operators from the stack
while (!stack.empty())
result.enqueue(stack.pop());
return result;
}
public static void main(String[] args)
{
QueueADT infix = new QueueADT();
String str = "a+b+c/(d+f)";
for(int i=0; i < str.length(); i++)
{
infix.enqueue(str.charAt(i));
System.out.print(str.charAt(i));
}
QueueADT postfix = infixToPostFix(infix);
System.out.println();
while(!postfix.empty())
{
System.out.print(postfix.dequeue());
}
}
}
Queue Class:
public class QueueADT
{
private int size;
private Node front;
private Node rear;
public QueueADT()
{
size = 0;
front = null;
rear = null;
}
public boolean empty()
{
return(size == 0);
}
public int size()
{
return size;
}
public void enqueue(char character)
{
Node newNode = new Node();
newNode.setData(character);
newNode.setNext(null);
if(this.empty())
{
front = newNode;
}
else
rear.setNext(newNode);
rear = newNode;
size++;
}
public char dequeue()
{
char i;
i = front.getData();
size--;
if(this.empty())
rear = null;
return i;
}
public char front()
{
return front.getData();
}
}
Stack class:
public class StackADT
{
private Node top;
private int size;
public StackADT()
{
top = null;
size = 0;
}
public boolean empty()
{
return (top == null);
}
public char peek()
{
return top.getData();
}
public int size()
{
return size;
}
public void push(char character)
{
Node newNode = new Node();
newNode.setData(character);
newNode.setNext(top);
top = newNode;
size++;
}
public char pop()
{
char i;
i = top.getData();
top = top.getNext();
size--;
return i;
}
public int onTop()
{
char i = pop();
push(i);
return i;
}
}
Node class:
public class Node
{
private char data;
private Node next;
public Node()
{
data = 0;
next = null;
}
public Node(char d)
{
data = d;
}
public Node(char d, Node n)
{
data = d;
next = n;
}
public void setData(char newData)
{
data = newData;
}
public void setNext(Node newNext)
{
next = newNext;
}
public char getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void displayNode()
{
System.out.print(data);
}
}
Your implementation of dequeue method in QueueADT class is incorrect. You never change field "front", that's why when you call that method in your case, 'a' is always being returned. Add
front = front.getNext();
after line
char i = front.getData();
There are more problems with that code - try testing each of your methods separately, not only the program as a whole.
I have to create a tree from a nested list of integers in Java, like this:
((3,8,(7,(3,0,7),(8,8,2))),
(4,(7,9,8),8),
(((3,6,4),2,6),((9,2,9),4,7,(6,4,5) ),4,(6,4,5))
)
would be parsed to this tree: https://gyazo.com/189e2a4936913f9025b501be86aabc35/
I just can't seem to visualize how the nested list becomes the tree...
NOTE, a blank space means the tree value is empty
It seems a node is either a leaf with a number, or a list of nodes:
public abstract class Node {
}
public class NumberNode extends Node {
private final int number;
public NumberNode(int number) {
this.number = number;
}
#Override
public String toString() {
return Integer.toString(number);
}
}
public class ListNode extends Node {
private final List<Node> list = new ArrayList<>();
public ListNode(Collection<Node> nodes) {
list.addAll(nodes);
}
#Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append('(');
boolean first = true;
for (Node node: list) {
if (first) {
first = false;
} else {
buf.append(',');
}
buf.append(node);
}
buf.append(')');
return buf.toString();
}
}
You may want to use a scanner to tokenize your input:
public class Scanner {
private final Reader in;
private int c;
private Token token;
private int number;
public static enum Token {LPAR,RPAR,NUMBER,COMMA,EOF};
public Scanner(Reader in) throws IOException {
this.in = in;
c = in.read();
}
public Token getToken() {
return token;
}
public int getNumber() {
return number;
}
public Token nextToken() throws IOException {
while (c == ' ') {
c = in.read();
}
if (c < 0) {
return token = Token.EOF;
}
if (c >= '0' && c <= '9') {
number = c - '0';
c = in.read();
while (c >= '0' && c <= '9') {
number = 10*number + (c-'0');
c = in.read();
}
return token = Token.NUMBER;
}
switch (c) {
case '(':
c = in.read();
return token = Token.LPAR;
case ')':
c = in.read();
return token = Token.RPAR;
case ',':
c = in.read();
return token = Token.COMMA;
default:
throw new RuntimeException("Unknown character " + c);
}
}
}
You can then write a parser:
public static Node parse(Reader in) throws IOException {
Scanner scanner = new Scanner(in);
scanner.nextToken();
return parse(scanner);
}
private static Node parse(Scanner scanner) throws IOException {
switch (scanner.getToken()) {
case NUMBER:
int value = scanner.getNumber();
scanner.nextToken();
return new NumberNode(value);
case LPAR:
scanner.nextToken();
List<Node> nodes = parseList(scanner);
if (scanner.getToken() != Token.RPAR) {
throw new RuntimeException(") expected");
}
scanner.nextToken();
return new ListNode(nodes);
default:
throw new RuntimeException("Number or ( expected");
}
}
private static List<Node> parseList(Scanner scanner) throws IOException {
List<Node> nodes = new ArrayList<>();
if (scanner.getToken() != Token.RPAR) {
nodes.add(parse(scanner));
while (scanner.getToken() == Token.COMMA) {
scanner.nextToken();
nodes.add(parse(scanner));
}
}
return nodes;
}
To parse your example:
String s = "((3,8,(7,(3,0,7),(8,8,2))), (4,(7,9,8),8), (((3,6,4),2,6),((9,2,9),4,7,(6,4,5) ),4,(6,4,5)) )";
System.out.println(s);
Node node = parse(new StringReader(s));
System.out.println(node);
Output:
((3,8,(7,(3,0,7),(8,8,2))), (4,(7,9,8),8), (((3,6,4),2,6),((9,2,9),4,7,(6,4,5) ),4,(6,4,5)) )
((3,8,(7,(3,0,7),(8,8,2))),(4,(7,9,8),8),(((3,6,4),2,6),((9,2,9),4,7,(6,4,5)),4,(6,4,5)))
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 ;-)