The idea is about serialize this box code. The program is to build flashcard and I want use serializetion to saving the state of the flashapp boxes, when the application exits into a file, and load the file on startup. So I don't have to redo all the flashcard from the beginning. The box code is as follow:
import java.util.ArrayList;
import java.util.Iterator;
public class Box implements java.io.Serializable {
private ArrayList<Flashcard> cards;
private double prossibility;
private double pivot; //determine the box's selected scope [pivot - prossibility,pivot)
public Box(){
cards = new ArrayList<Flashcard>();
prossibility = 0.0;
pivot = 0.0;
}
public Box(double prossibility,double pivot){
this.cards = new ArrayList<Flashcard>();
this.prossibility = prossibility;
this.pivot = pivot;
}
public Box(ArrayList<Flashcard> cards){
this.cards = cards;
}
public ArrayList<Flashcard> getCards() {
return cards;
}
public void setProssibility(double prossibility){
this.prossibility = prossibility;
}
public double getProssibility(){
return prossibility;
}
public void setPivot(double pivot){
this.pivot = pivot;
}
public double getPivot(){
return pivot;
}
public void addCard(Flashcard card){
cards.add(card);
}
public int searchCard(String challenge){
Iterator<Flashcard> it = cards.iterator();
int index = 0;
while(it.hasNext()){
Flashcard temp = (Flashcard)it.next();
if(temp.getChallenge().equals(challenge)){
break;
}
++index;
}
if(index >= cards.size())
index = -1;
return index;
}
public void removeCard(String challenge){
int index = searchCard(challenge);
if(index >= 0)
cards.remove(index);
}
}
My flashcard class is like:
enum ESide{
FRONT, //challenge side
BACK //response side
};
public class Flashcard implements Cloneable{
private String challenge;
private String response;
private ESide side;
private int boxIndex;
public Flashcard(){
challenge = new String();
response = new String();
side = ESide.BACK;
boxIndex = 0;
}
public Flashcard(String challenge, String response, ESide side){
this.challenge = challenge;
this.response = response;
this.side = side;
this.boxIndex = 0;
}
public Flashcard(String challenge, String response){
this.challenge = challenge;
this.response = response;
this.side = ESide.BACK;
this.boxIndex = 0;
}
public void setChallenge(String challenge){
this.challenge = challenge;
}
public String getChallenge(){
return challenge;
}
public void setResponse(String response){
this.response = response;
}
public String getResponse(){
return response;
}
public void setSide(ESide side){
this.side = side;
}
public ESide getSide(){
return side;
}
public void setBoxIndex(int index){
this.boxIndex = index;
}
public int getBoxIndex(){
return boxIndex;
}
public void flipSide(){
if(side == ESide.BACK)
side = ESide.FRONT;
else
side = ESide.BACK;
}
public Object clone(){
Flashcard o = null;
try {
o = (Flashcard)super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return o;
}
public boolean equals(Object o){
if(this == o)
return true;
if(o == null)
return false;
if(!(o instanceof Flashcard))
return false;
Flashcard temp = (Flashcard)o;
if(!temp.challenge.equals(this.challenge) || !temp.response.equals(this.response)){
return false;
}
return true;
}
}
The serialize code I have done is like this:
import java.io.*;
public class Savingbox implements Serializable {
public static void main(String[] args){
Box e = new Box();
So how can I make the savingbox class save the result that the user just used?
From what I understand you want to save the Flashcard objects to a file and then read those back in. Here is a link that explains how to: How to write and read java serialized objects into a file
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 have got an array of 20:
private Karte[] deckArr;
deckArr = new Karte[20];
Now I want to sort the array by card-names every time a new card is added.
P.S. the cards are added 1 by 1 after clicking on a button, so there are empty spaces in the array.
Since the...
Arrays.sort(deckArr.getName());
...method does not work here I asked myself how it is done.
Karte(card) class:
package Model;
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements ComparableContent<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
#Override
public boolean isLess(Karte karte) {
if (getName().compareTo(karte.getName()) < 0){
return true;
}else{
return false;
}
}
#Override
public boolean isEqual(Karte karte) {
return getName() == karte.getName();
}
#Override
public boolean isGreater(Karte karte) {
if (getName().compareTo(karte.getName()) > 0){
return true;
}else{
return false;
}
}
}
Any help is appreciated!
Why not just use ArrayList instead? Easier to add, remove elements and you will never have empty slots.
Anyway to sort you can use Collections.sort like this:
deckArr = new ArrayList<Karte>();
Collections.sort(deckArr, Comparator.comparing(karte -> karte.getName()));
Java 8 offers a simple solution:
The Comparable Interface has a static method that creates a Comaprator with an extractor.
Comparator<Card> comp = Comparator.comparing(Karte::getName);
With this using a sorting method (e.g. Arrays.sort) is easy to call.
On top of that, to solve your nullpointer problem, the Comparator Interface offers another two functions: NullsLast and nullsFirst.
Comparator<Card> comp = Comparator.nullsLast(Comparator.comparing(Card::getName));
For me this looks like the easiest solution to your question :)
This should solve your problem. Implements the Comparable interface.
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements Comparable<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
public int compareTo(Karte karte) {
return this.name.compareTo(karte.getName());
}
}
Then you just need to call Arrays.sort(deckArr);
You need to check for nulls and just call below--
Arrays.sort(deckArr, new Comparator<Karte>() {
#Override
public int compare(Karte karte1, Karte karte2) {
if (karte1.getName() == null && karte2.getName() == null) {
return 0;
}
if (karte1.getName() == null) {
return 1;
}
if (karte2.getName() == null) {
return -1;
}
return karte1.getName().compareTo(karte2.getName());
}});
I have been trying to translate this tutorial into Java code, as I want to make a simple game with level/achievements in android (and haven't found as thorough/basic examples in java online, if you have one please share)
Please help me understand:
How can I link different file of classes together? in the example they don't seem to refer to each other? Basically how can I pass on the properties and settings from the tasks/games to these functions which are elsewhere in the code? do I just refer to the class several times throughout the code?
For example I am stuck in this part, could use help in understanding how this works in java code? (examples are most appreciated)
> private var mProps :Object; // dictionary of properties
private var mAchievements :Object; // dictionary of achievements
public function Achieve() {
mProps = { };
mAchievements = { };
}
public function defineProperty(theName :String, theInitialValue :int, theaActivationMode :String, theValue :int) :void {
mProps[theName] = new Property(theName, theInitialValue, theaActivationMode, theValue);
}
public function defineAchievement(theName :String, theRelatedProps :Array) :void {
mAchievements[theName] = new Achievement(theName, theRelatedProps);
}
Remember that each class must go to its own file.
public class Property {
private String mName;
private int mValue;
private String mActivation;
private int mActivationValue;
private int mInitialValue;
public Property(String theName, int theInitialValue, String theActivation, int theActivationValue) {
mName = theName;
mActivation = theActivation;
mActivationValue = theActivationValue;
mInitialValue = theInitialValue;
}
public int getValue() {
return mValue;
}
public void setValue(int n) {
mValue = n;
}
public boolean isActive() {
boolean aRet = false;
switch(mActivation) {
case Achieve.ACTIVE_IF_GREATER_THAN: aRet = mValue > mActivationValue; break;
case Achieve.ACTIVE_IF_LESS_THAN: aRet = mValue < mActivationValue; break;
case Achieve.ACTIVE_IF_EQUALS_TO: aRet = mValue == mActivationValue; break;
}
return aRet;
}
public String getActivation() {
return mActivation;
}
}
import java.util.ArrayList;
public class Achievement {
private String mName; // achievement name
private ArrayList<String> mProps; // array of related properties
private boolean mUnlocked; // achievement is unlocked or not
public Achievement(String theId, ArrayList<String> theRelatedProps) {
mName = theId;
mProps = theRelatedProps;
mUnlocked = false;
}
public boolean isUnlocked() {
return mUnlocked;
}
public void setUnlocked(boolean b) {
mUnlocked = b;
}
public ArrayList<String> getProps() {
return mProps;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Achieve {
// activation rules
public static final String ACTIVE_IF_GREATER_THAN = ">";
public static final String ACTIVE_IF_LESS_THAN = "<";
public static final String ACTIVE_IF_EQUALS_TO = "==";
private HashMap<String,Property> mProps; // dictionary of properties
private HashMap<String,Achievement> mAchievements; // dictionary of achievements
public Achieve() {
mProps = new HashMap<String,Property>();
mAchievements = new HashMap<String,Achievement>();
}
public void defineProperty(String theName, int theInitialValue, String theaActivationMode, int theValue) {
mProps.put(theName, new Property(theName, theInitialValue, theaActivationMode, theValue));
}
public void defineAchievement(String theName, ArrayList<String> theRelatedProps) {
mAchievements.put(theName, new Achievement(theName, theRelatedProps));
}
public int getValue(String theProp) {
Property p = mProps.get(theProp);
if (p != null) return p.getValue();
return 0;
}
public void setValue(String theProp, int theValue) {
Property p = mProps.get(theProp);
if (p == null) return;
switch(p.getActivation()) {
case Achieve.ACTIVE_IF_GREATER_THAN:
theValue = theValue > p.getValue() ? theValue : p.getValue();
break;
case Achieve.ACTIVE_IF_LESS_THAN:
theValue = theValue < p.getValue() ? theValue : p.getValue();
break;
}
p.setValue(theValue);
}
public void addValue(ArrayList<String> theProps, int theValue) {
for (int i = 0; i < theProps.size(); i++) {
String aPropName = theProps.get(i);
setValue(aPropName, getValue(aPropName) + theValue);
}
}
public ArrayList<Achievement> checkAchievements() {
ArrayList<Achievement> aRet = new ArrayList<Achievement>();
Iterator<Map.Entry<String,Achievement>> it = mAchievements.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String,Achievement> pair = it.next();
Achievement aAchievement = pair.getValue();
if (!aAchievement.isUnlocked()) {
int aActiveProps = 0;
ArrayList<String> props = aAchievement.getProps();
for (int p = 0; p < props.size(); p++) {
Property aProp= mProps.get(props.get(p));
if (aProp.isActive()) {
aActiveProps++;
}
}
if (aActiveProps == props.size()) {
aAchievement.setUnlocked(true);
aRet.add(aAchievement);
}
}
}
return aRet;
}
}
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 ;-)
I'm using Eclipse and I'm using Java. My objective it's to sort a vector, with the bogoSort method
in one vector( vectorExample ) adapted to my type of vector and use the Java sort on other vector (javaVector) and compare them.
I did the tests but it did't work, so I don't know what is failing.
*Note: there are few words in spanish: ordenado = sorted, Ejemplo = Example, maximo = maximun, contenido = content.
EjemploVector class
package vector;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.Iterator;
public class EjemploVector <T> {
protected T[] contenido;
private int numeroElementos;
#SuppressWarnings("unchecked")
public EjemploVector () {
contenido = (T[]) new Object[100];
numeroElementos = 0;
}
#SuppressWarnings("unchecked")
public EjemploVector (int maximo) {
contenido = (T[]) new Object[maximo];
numeroElementos = 0;
}
public String toString(){
String toString="[";
for (int k=0; k<numeroElementos;k++){
if (k==numeroElementos-1){
toString = toString + contenido[k].toString();
} else {
toString = toString + contenido[k].toString()+", ";
}
}
toString = toString + "]";
return toString;
}
public boolean equals (Object derecho){
if (!(derecho instanceof Vector<?>)) {
return false;
} else if (numeroElementos != ((Vector<?>)derecho).size()) {
return false;
} else {
Iterator<?> elemento = ((Vector<?>)derecho).iterator();
for (int k=0; k<numeroElementos;k++){
if (!((contenido[k]).equals (elemento.next()))) {
return false;
}
}
return true;
}
}
public void addElement (T elemento){
contenido[numeroElementos++]= elemento;
}
protected T[] getContenido(){
return this.contenido;
}
protected T getContenido (int k){
return this.contenido[k];
}
#SuppressWarnings("unchecked")
protected void setContenido (int k, Object elemento){
this.contenido[k]= (T)elemento;
}
EjemploVectorOrdenadoClass
package vector.ordenado;
import java.util.Arrays;
import java.util.Random;
import vector.EjemploVector;
public class EjemploVectorOrdenado<T extends Comparable<T>> extends EjemploVector<T> {
private boolean organized;
public EjemploVectorOrdenado() {
super();
organized = true;
}
public EjemploVectorOrdenado(int maximo) {
super(maximo);
organized = true; //
}
public boolean getOrdenado() {
return this.organized;
}
// Method bogoSort
public void bogoSort() {
if (!this.organized) {
if (this.size() > 0) {
Random generator;
T tempVariable;
int randomPosition;
do {
generator = new Random();
for (int i = 0; i < this.size(); i++) {
randomPosition = generator.nextInt(this.size());
tempVariable = contenido[i];
contenido[i] = contenido[randomPosition];
contenido[randomPosition] = tempVariable;
}
} while (!organized);
}
}
this.organized = true;
}
public void addElement(T elemento) {
super.addElement(elemento);
if (organized && this.size() > 1) {
T penultimo = this.getContenido(this.size() - 2);
T ultimo = this.getContenido(this.size() - 1);
organized = penultimo.compareTo(ultimo) <= 0;
}
}
}
ElementoTest class
package elementos;
import java.io.Serializable;
public class ElementoTest implements Comparable<ElementoTest>, Serializable {
private static final long serialVersionUID = -7683744298261205956L;
private static int numeroElementosTest = 0;
private int clave;
private int valor;
public ElementoTest(int i){
this.clave = i;
this.valor = numeroElementosTest;
numeroElementosTest++;
}
public String toString(){
return ("(" + this.clave + "," + this.valor + ")");
}
public boolean equals (Object derecho){
if (!(derecho instanceof ElementoTest)) {
return false;
} else {
return clave == ((ElementoTest)derecho).clave;
}
}
public char getClave(){
return this.clave;
}
public int getValor(){
return this.valor;
}
#Override
public int compareTo(ElementoTest elemento) {
if (elemento == null){
return -1;
} else if (this.equals(elemento)){
return 0;
} else if (clave < elemento.clave){
return -1;
} else {
return 1;
}
}
}
TESTS
The first it's a stupid test, because it puts elements in order so... really the methods aren´t doing anything, java just compare and it gives correct
I tried to make an unsorted vector adding elements but there appears the java.lang.ClassCastException: [Ljava.... etc.
package vector.ordenado;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.Vector;
import org.junit.Before;
import org.junit.Test;
import elementos.ElementoTest;
public class EjemploVectorOrdenadoTest {
private Vector<ElementoTest> vectorJava;
private EjemploVectorOrdenado<ElementoTest> vectorExample;
#Before
public void setUp() throws Exception {
vectorJava = new Vector<ElementoTest>(100);
vectorExample = new EjemploVectorOrdenado<ElementoTest>(100);
}
#Test
public void testSortFailTest() {
for (char c = 'a'; c < 'g'; c++) {
vectorJava.addElement(new ElementoTest(c));
vectorExample.addElement(new ElementoTest(c));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
#Test
public void testSort() {
{
vectorJava.addElement(new ElementoTest(1));
vectorJava.addElement(new ElementoTest(3));
vectorJava.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(3));
vectorExample.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(1));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
}
Sorry, for the problems and thanks.
The problem is that your test class ElementoTest should implement the Comparable interface. Or you need to provide a Comparator during your comparison.
Does your class ElementtoTest implement Comparable?
If not, it needs to.
I'm suspecting it doesn't, because that's exactly what would cause this error. you'll need to add implements Comparable and then override the int compareTo(Elementtotest e) method, where you specify what criteria you'd like to order the objects based on.