Comparing words - java

I have problem with my code. I wrote program for count words in text, but I have small problem with patterns which must be search in text. Maybe somebody can help me.
import java.util.*;
class KomparatorLicz implements Comparator<Word> {
#Override
public int compare(Word arg0, Word arg1) {
return arg1.amount - arg0.amount;
}
}
class KomparatorString implements Comparator<Word> {
#Override
public int compare(Word obj1, Word obj2) {
if (obj1.content == obj2.content) {
return 0;
}
if (obj1.content == null) {
return -1;
}
if (obj2.content == null) {
return 1;
}
return obj1.content.compareTo(obj2.content);
}
}
class Word
{
public String content;
public int amount;
public Word(String content, int amount) {
this.content = content;
this.amount = amount;
}
#Override
public String toString() {
return "Word [content=" + content + ", amount=" + amount + "]";
}
}
public class Source4 {
public static float procent(int wordCount, int oneWord)
{
return (((float)oneWord*100)/(float)wordCount);
}
public static void main(String[] args) {
String line, wordsLine[];
String klucze = null;
int valTemp;
int wordCount=0;
int keyWords=0;
HashMap<String, Word> slownik = new HashMap<String, Word>();
ArrayList<Word> lista= new ArrayList<Word>();
ArrayList<Object> keyWordsList = new ArrayList<Object>();
Scanner in = new Scanner(System.in);
String alph = in.nextLine();
keyWords = in.nextInt();
for(int i=0; i<keyWords; i++)
{
klucze = in.next();
keyWordsList.add(klucze);
}
while(in.hasNextLine())
{
line = in.nextLine();
if(line.equals("koniec")) break;
wordsLine = line.split("[^" + alph + "]");
for(String s : wordsLine) {
if(s != null && s.length() > 0)
{
wordCount++;
if(slownik.containsKey(s))
{
valTemp = slownik.get(s).amount;
slownik.remove(s);
valTemp++;
slownik.put(s, new Word(s,valTemp));
}
else
{
slownik.put(s, new Word(s,1));
}
}
}
}
for (String key : slownik.keySet())
{
lista.add(slownik.get(key));
}
Collections.sort(lista, new KomparatorString());
StringBuffer result = new StringBuffer();
int keyWordCounter=0;
int amountBuff=0;
float percentBuff=0;
for (int i = 0; i<lista.size();i++)
{
if(keyWordsList.contains(lista.get(i)))
{
result.append(amountBuff+" "+percentBuff+"%");
amountBuff = 0;
percentBuff = 0;
result.append("\n");
result.append(lista.get(i).amount+" "+(procent(wordCount,lista.get(i).amount)+"%"));
result.append(" "+lista.get(i).content);
result.append("\n");
keyWordCounter+=lista.get(i).amount;
}
else
{
amountBuff+=lista.get(i).amount;
percentBuff+=procent(wordCount,lista.get(i).amount);
}
}
result.append(amountBuff+" "+percentBuff+"%");
System.out.println("Wersja AK");
System.out.println(keyWords+" różnych słów kluczowych");
System.out.println(wordCount+" wystąpień wszystkich słów");
System.out.println(keyWordCounter+" "+procent(wordCount,keyWordCounter)+"% "+" wystąpień słów kluczowych");
System.out.println((wordCount-keyWordCounter)+" "+procent(wordCount,(wordCount-keyWordCounter))+"% wystąpień innych słów");
System.out.println(result);
}
}

It's wrong code if(keyWordsList.contains(lista.get(i))).
You need if(keyWordsList.contains(lista.get(i).content)).

Related

How to merge two alike items within the ArrayList?

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?

How to get all possible combinations of substrings?

I have a String of following structure:
A1(N1,N2,N3)P4(O3,O5)Y1.
How to get all combinations? The rule is that options inside parenthesis should not go together. For this example the output should be:
A1N1P4O3Y1,
A1N2P4O3Y1,
A1N3P4O3Y1,
A1N1P4O5Y1,
A1N2P4O5Y1,
A1N3P4O5Y1.
There can be parenthesis, but it can be without it. Another example:
N3P5(L1,L2)Q1, output should be:
N3P5L1Q1,
N3P5L2Q1.
Anyone with elegant solution?
The main idea is to transform a string input into a StringTemplate that holds parts, that can be a single string or a group of strings.
For each part, a iterator is created. While some iterator can go next, update a string array that holds current part values and reset all iterators of parts that come before the part that changed. Feel free to clear repeated code and add nested groups support and syntax verifications if needed.
private static StringTemplate parse(String string) {
List<StringPart> parts = new ArrayList<StringPart>();
boolean insideGroup = false;
StringBuilder currentToken = new StringBuilder();
List<LiteralPart> groupParts = new ArrayList<LiteralPart>();
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if (ch == '(') {
if (currentToken.length() != 0) {
parts.add(new LiteralPart(currentToken.toString()));
currentToken.delete(0, currentToken.length());
}
insideGroup = true;
} else if (ch == ')') {
if (insideGroup) {
if (currentToken.length() != 0) {
groupParts.add(new LiteralPart(currentToken.toString()));
currentToken.delete(0, currentToken.length());
}
parts.add(new CompositePart(groupParts));
groupParts.clear();
insideGroup = false;
} else {
currentToken.append(ch);
}
} else if (ch == ',') {
if (insideGroup) {
if (currentToken.length() != 0) {
groupParts.add(new LiteralPart(currentToken.toString()));
currentToken.delete(0, currentToken.length());
}
} else {
currentToken.append(ch);
}
} else {
currentToken.append(ch);
}
}
if (currentToken.length() != 0) {
parts.add(new LiteralPart(currentToken.toString()));
currentToken.delete(0, currentToken.length());
}
return new StringTemplate(parts);
}
private static final class StringTemplate {
private final List<StringPart> parts;
public StringTemplate(List<StringPart> parts) {
this.parts = parts;
}
public List<String> getCombinations() {
List<Iterator<String>> iterators = new ArrayList<Iterator<String>>(parts.size());
for (StringPart part : parts) {
iterators.add(part.getStrings().iterator());
}
String[] toJoin = new String[iterators.size()];
List<String> combinations = new ArrayList<String>();
int iteratorThatAdvanced;
int maxIteratorThatAdvanced = Integer.MIN_VALUE;
boolean first = true;
for (;;) {
iteratorThatAdvanced = -1;
for (int i = 0; i < iterators.size(); i++) {
Iterator<String> iterator = iterators.get(i);
if (first || iterator.hasNext()) {
String value = iterator.next();
toJoin[i] = value;
iteratorThatAdvanced = i;
if (!first && i >= maxIteratorThatAdvanced) {
maxIteratorThatAdvanced = i;
break;
}
}
}
if (iteratorThatAdvanced < 0) {
break;
}
if (!first) {
for (int i = 0; i < iteratorThatAdvanced; i++) {
Iterator<String> iterator = parts.get(i).getStrings().iterator();
iterators.set(i, iterator);
toJoin[i] = iterator.next();
}
}
combinations.add(join(toJoin));
first = false;
}
return combinations;
}
}
private static String join(String[] strings) {
StringBuilder builder = new StringBuilder();
for (String string : strings) {
builder.append(string);
}
return builder.toString();
}
private static abstract class StringPart {
abstract List<String> getStrings();
}
private static final class LiteralPart extends StringPart {
private final String literal;
public LiteralPart(String literal) {
this.literal = literal;
}
#Override
List<String> getStrings() {
return Collections.singletonList(literal);
}
}
private static final class CompositePart extends StringPart {
private final List<LiteralPart> parts;
public CompositePart(List<LiteralPart> parts) {
this.parts = new ArrayList<LiteralPart>(parts);
}
#Override
List<String> getStrings() {
List<String> strings = new ArrayList<String>(parts.size());
for (LiteralPart part : parts) {
strings.add(part.literal);
}
return strings;
}
}
Example:
public static void main(String[] args) {
StringTemplate template = parse("A1(N1,N2,N3)P4(O3,O5)Y1");
for (String combination : template.getCombinations()) {
System.out.println(combination);
}
template = parse("N3P5(L1,L2)Q1");
for (String combination : template.getCombinations()) {
System.out.println(combination);
}
}

Dates sorting fix?

class Datum {
public final Integer dan;
public final Integer mesec;
public final Integer godina;
public Datum(String datum) {
String[] komponente = datum.split("\\.");
dan = Integer.valueOf(komponente[0]);
mesec = Integer.valueOf(komponente[1]);
godina = Integer.valueOf(komponente[2]);
}
#Override
public String toString() {
return dan + "." + mesec + "." + godina + ".";
}
}
public class DomaciZadatakZaMozganje1 {
public static void main(String[] args) {
Datum[] datumi = new Datum[] {
new Datum("11.4.2015."),
new Datum("12.5.2013."),
new Datum("21.5.2015."),
new Datum("11.4.2014."),
new Datum("14.4.2015."),
new Datum("14.4.2014."),
new Datum("21.4.2015."),
new Datum("12.5.2014."),
new Datum("11.4.2013."),
new Datum("12.5.2015."),
new Datum("14.4.2013."),
new Datum("16.5.2015.")
};
Svetovid.out.println("Unsorted :");
for (Datum datum : datumi) {
Svetovid.out.println(datum);
}
Arrays.sort(datumi, new KomparatorDatuma());
Svetovid.out.println("Sorted: ");
for (Datum datum : datumi) {
Svetovid.out.println(datum);
}
}
}
class KomparatorDatuma implements Comparator<Datum> {
private Comparator<Integer> komparator = new ObrnutiKomparatorBrojeva();
#Override
public int compare(Datum datum1, Datum datum2) {
int rezultat = komparator.compare(datum1.godina, datum2.godina);
if (rezultat == 0)
rezultat = komparator.compare(datum1.mesec, datum2.mesec);
if (rezultat == 0)
rezultat = komparator.compare(datum1.dan, datum2.dan);
return rezultat;
}
}
class ObrnutiKomparatorBrojeva implements Comparator<Integer> {
#Override
public int compare(Integer int1, Integer int2) {
if (int1 == int2) {
return 0;
} else if (int1 < int2) {
return 1;
} else {
return -1;
}
}
}
Result of this sort is:
14.4.2013.
11.4.2013.
12.5.2013.
12.5.2014.
14.4.2014.
11.4.2014.
16.5.2015.
12.5.2015.
21.4.2015.
14.4.2015.
21.5.2015.
11.4.2015.
Why this doesn't work?
you have small problem with compare method if (int1 == int2) will not compare values but references, try this one:
public int compare(final Integer int1, final Integer int2) {
return int2.compareTo(int1);
}

Array required, but Java.lang.string found String error

I am trying to use a 2D array to create JTable. When assigning the values for the columns in the JTable I get the Java.lang.String found error. The data type of the variables are also String and the 2D array is also of type String.
import java.io.*;
import java.util.*;
/**
* Write a description of class PhoneBook here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class PhoneBook
{
static PhoneBookEntry contacts[] = new PhoneBookEntry[100];
int a=0;
int b[] = new int [100];
int count=0;
public void getData()throws IOException
{
FileReader in = new FileReader("phonebookinput.txt");
BufferedReader textreader = new BufferedReader(in);
String sp[];
for(a=0; a<contacts.length; a++)
{
String s = textreader.readLine();
sp = s.split("\t");
contacts[a] = new PhoneBookEntry(sp[0], sp[1], (Integer.parseInt(sp[2])), sp[3], sp[4]);
}
}
public void add(String z, String x, int c, String d, String e)
{
for (int t=0; t<b.length; t++)
{
if (contacts[b[t]].getNumber().equals("XXXX"))
{
contacts[b[t]] = new PhoneBookEntry(z, x, c, d, e);
}
else
{
contacts[a+1] = new PhoneBookEntry(z, x, c, d, e);
a++;
}
}
}
public int searchName(String n)
{
int y=-1;
for (int b=0; b<contacts.length;b++)
{
if (contacts[b].getFirstName().equalsIgnoreCase(n))
{
y=b;
}
else if (contacts[b].getLastName().equalsIgnoreCase(n))
{
y=b;
}
}
return y;
}
public int searchNumber(String m)
{
int x=-1;
for(int d=0; d<contacts.length; d++)
{
if (contacts[d].getNumber().startsWith(m))
{
x=d;
}
else if (contacts[d].getNumber().endsWith(m))
{
x=d;
}
}
return x;
}
public boolean edit(String a, String b, int c, String d, String e, String f)
{
int g=searchName(f);
int h=searchNumber(f);
if (g!=-1)
{
contacts[g].setFirstName(a);
contacts[g].setLastName(b);
contacts[g].setAge(c);
contacts[g].setNumber(d);
contacts[g].setEmail(e);
return true;
}
else if (h!=-1)
{
contacts[h].setFirstName(a);
contacts[h].setLastName(b);
contacts[h].setAge(c);
contacts[h].setNumber(d);
contacts[h].setEmail(e);
return true;
}
else {return false;}
}
public void deleteValue(String u)
{
int g=searchName(u);
int h=searchNumber(u);
if (g!=-1)
{
contacts[g].setFirstName("XXXX");
contacts[g].setLastName("XXXX");
contacts[g].setAge(-1);
contacts[g].setNumber("XXXX");
contacts[g].setEmail("XXXX");
b[count]=g;
}
else if (h!=-1)
{
contacts[h].setFirstName("XXXX");
contacts[h].setLastName("XXXX");
contacts[h].setAge(-1);
contacts[h].setNumber("XXXX");
contacts[h].setEmail("XXXX");
b[count]=h;
}
count = count + 1;
}
public void sortFirstName()
{
for (int r=99; r>=0; r--)
{
for (int h=0; h<=r-1; h++)
{
if (contacts[h].getFirstName().compareTo(contacts[h+1].getFirstName())>0)
{
String temp = contacts[h+1].getFirstName();
contacts[h+1].setFirstName(contacts[h].getFirstName());
contacts[h].setFirstName(temp);
}
}
}
}
public void sortLastName()
{
for (int r=99; r>=0; r--)
{
for (int h=0; h<=r-1; h++)
{
if (contacts[h].getLastName().compareTo(contacts[h+1].getLastName())>0)
{
String temp = contacts[h+1].getLastName();
contacts[h+1].setLastName(contacts[h].getLastName());
contacts[h].setLastName(temp);
}
}
}
}
public void printDetails()
{
String [] columnNames = {"First Name", "Last Name", "Age", "Phone Number", "Email"};
String data [][] = new String [100][5];
for (int u=0; u<data.length; u++)
{
String first = contacts[u].getFirstName();
String last = contacts[u].getLastName();
String age = Integer.toString(contacts[u].getAge());
String number = contacts[u].getNumber();
String email = contacts[u].getEmail();
columnNames[u][0] = first; //Here is where the error comes
columnNames[u][1] = last;
columnNames[u][2] = age;
columnNames[u][3] = number;
columnNames[u][4] = email;
}
JTable table = new JTable (data, columnNames);
table.setEnabled(false);
}
}
columnNames in your code above is a one dimensional String array, but you're attempting to use it as a two dimensional array
columnNames[u][0] = first; //Here is where the error comes
I think you meant to assign values in your loop to the data array instead of the columnNames array, as in
data[u][0] = first;

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