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);
}
Related
This question already has answers here:
How to sort ip address in ascending order
(10 answers)
Closed 6 years ago.
How do i sort the ipranges in java
For Example:
My input is a string of IpRange Address i.e
9.9.9.9/12
100.0.0.0/12
8.8.8.8/12
1.2.3.4/32
1.2.2.2/12
12.3.1.45/12
My Output Should be
1.2.2.2/12
1.2.3.4/32
8.8.8.8/12
9.9.9.9/12
12.3.1.45/12
100.0.0.0/12
TIA
You can write your own comparator. Looks to be an easy task. This is also shared in one the blogs. Following is very bare implementation of the same (only indicative),
public class TestIPSorter {
#Test
public void test() {
String[] input = {"9.9.9.9/12" ,"100.0.0.0/12" ,"8.8.8.8/12" ,"1.2.3.4/32" ,"1.2.2.2/12", "12.3.1.45/12"};
String[] expectedOutput = {"1.2.2.2/12" ,"1.2.3.4/32", "8.8.8.8/12" ,"9.9.9.9/12" ,"12.3.1.45/12", "100.0.0.0/12"};
String[] sortedIp = IPSorter.sort(input);
Assert.assertArrayEquals(expectedOutput, sortedIp);
}
}
public class IPSorter {
public static String[] sort(String[] input) {
IpAddress[] array = Arrays.stream(input).map(i -> IpAddress.valueOf(i)).toArray(IpAddress[]::new);
Arrays.sort(array);
return Arrays.stream(array).map(ipAd -> ipAd.getAddress()).toArray(String[]::new);
}
private static class IpAddress implements Comparable<IpAddress> {
private final String original;
private final String ipStart;
private final int to;
private IpAddress(String address) {
int forwardSlash = address.lastIndexOf("/");
ipStart = address.substring(0, forwardSlash);
to = Integer.parseInt(address.substring(forwardSlash + 1));
original = address;
}
static IpAddress valueOf(String address) {
return new IpAddress(address);
}
String getAddress() {
return original;
}
#Override
public int compareTo(IpAddress o) {
try {
byte[] ba1 = InetAddress.getByName(this.ipStart).getAddress();
byte[] ba2 = InetAddress.getByName(o.ipStart).getAddress();
// general ordering: ipv4 before ipv6
if (ba1.length < ba2.length)
return -1;
if (ba1.length > ba2.length)
return 1;
// we have 2 ips of the same type, so we have to compare each byte
for (int i = 0; i < ba1.length; i++) {
int b1 = unsignedByteToInt(ba1[i]);
int b2 = unsignedByteToInt(ba2[i]);
if (b1 == b2)
continue;
if (b1 < b2) {
return -1;
} else {
return 1;
}
}
return compareRange(to, o.to);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
private int compareRange(int range1, int range2) {
return Integer.compare(range1, range2);
}
private int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
}
}
I have an arraylist with below string elements -->
['STM-1000-H', 'STM-2000-E', 'STM-4000-H', 'STM-200-H', 'SFP-1000-A',
'SFP-300-H', 'SAFPX-1000-H', 'SAFPX-2000-A', 'STM-1000-H-L1', 'STM-1000-H-L1+VA+GH', 'STM-1000-H-L2']
I want an arraylist with grouping like ...
display STM- 400, 500, 600, 100, 2000, 4000 (in that order), followed by SPX- 1000, 2000, 4000 (in that order, then followed by the SAFPX- 1000. Also, I have to list each by the L, L1, L2, M, M1, M2, M3, H, H! and VH (in that Order).
Can you please assist with this, Array list is string elements only.
You should create a custom comparator and then use that to sort the arraylist.
For example (this does some of the sorting you asked for but is not checked for edge-cases, that is up to you to fix). Note: Java 8 is used
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("STM-1000-H");
list.add("STM-2000-E");
list.add("SAFPX-1000-H-L2");
list.add("SAFPX-1000-H-L1");
list.add("STM-1000-H-L1");
list.add("SFP-1000-B");
list.add("SFP-1000-A");
HashMap hm = new HashMap();
hm.put("STM", 1);
hm.put("SFP", 2);
hm.put("SAFPX", 3);
list = sort(list, hm);
for (String s : list) {
System.out.println(s);
}
}
public static ArrayList<String> sort(ArrayList<String> list, HashMap<String, Integer> hashmap) {
Comparator<String> comparator = (string1, string2) ->
{
String[] tokens1 = string1.split("-");
String[] tokens2 = string2.split("-");
if (hashmap.get(tokens1[0]) > hashmap.get(tokens2[0]))
return 1;
else if (hashmap.get(tokens1[0]) < hashmap.get(tokens2[0]))
return -1;
if (Integer.parseInt(tokens1[1]) > Integer.parseInt(tokens2[1]))
return 1;
else if (Integer.parseInt(tokens1[1]) < Integer.parseInt(tokens2[1]))
return -1;
if (tokens1.length > 2 && tokens2.length > 2) {
int res = tokens1[2].compareTo(tokens2[2]);
if(res != 0)
return res;
}
if (tokens1.length > 3 && tokens2.length > 3) {
int res = tokens1[3].compareTo(tokens2[3]);
if(res != 0)
return res;
}
return 0;
};
Collections.sort(list, comparator);
return list;
}
Outputs:
STM-1000-H
STM-1000-H-L1
STM-2000-E
SFP-1000-A
SFP-1000-B
SAFPX-1000-H-L1
SAFPX-1000-H-L2
Stream.of("STM-1000-H",
"STM-2000-E",
"STM-4000-H",
"STM-200-H",
"SFP-1000-A",
"SFP-300-H",
"SAFPX-1000-H",
"SAFPX-2000-A",
"STM-1000-H-L1",
"STM-1000-H-L1+VA+GH",
"STM-1000-H-L2")
.collect(Collectors.groupingBy(s -> s.substring(0, s.indexOf('-'))))
.entrySet()
.stream()
.sorted((e1, e2) -> -e1.getKey().compareTo(e2.getKey()))
.forEach(e -> {
System.out.println(e.getKey() + ":");
e.getValue().stream().sorted().forEach(System.out::println);
});
--
STM:
STM-1000-H
STM-1000-H-L1
STM-1000-H-L1+VA+GH
STM-1000-H-L2
STM-200-H
STM-2000-E
STM-4000-H
SFP:
SFP-1000-A
SFP-300-H
SAFPX:
SAFPX-1000-H
SAFPX-2000-A
package com.skadakov.examples.devrev;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
/**
*
* #author s.kadakov
*/
public class DevRev {
private final String series;
private final int model;
private final String version;
private final String revision;
public DevRev(String firmware) {
String[] ss = firmware.split("-");
if (ss.length < 3) {
throw new IllegalArgumentException(firmware);
}
this.series = ss[0];
this.model = Integer.parseInt(ss[1]);
this.version = ss[2];
this.revision = ss.length == 3 ? null : ss[3];
}
public String getSeries() {
return series;
}
public int getModel() {
return model;
}
public String getVersion() {
return version;
}
public String getRevision() {
return revision;
}
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + Objects.hashCode(this.series);
hash = 97 * hash + this.model;
hash = 97 * hash + Objects.hashCode(this.version);
hash = 97 * hash + Objects.hashCode(this.revision);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DevRev other = (DevRev) obj;
if (this.model != other.model) {
return false;
}
if (!Objects.equals(this.series, other.series)) {
return false;
}
if (!Objects.equals(this.version, other.version)) {
return false;
}
return Objects.equals(this.revision, other.revision);
}
#Override
public String toString() {
return series + "-" + model + "-" + version + (revision != null ? "-" + revision : "");
}
public static void main(String[] args) {
String[] firmare = {
"STM-1000-H",
"STM-2000-E",
"STM-4000-H",
"STM-200-H",
"SFP-1000-A",
"SFP-300-H",
"SAFPX-1000-H",
"SAFPX-2000-A",
"STM-1000-H-L1",
"STM-1000-H-L1+VA+GH",
"STM-1000-H-L2"};
Map<String, List<DevRev>> revs = new TreeMap<>();
for (String f : firmare) {
DevRev dr = new DevRev(f);
List<DevRev> sdevs = revs.get(dr.getSeries());
if (sdevs == null) {
sdevs = new ArrayList<>();
revs.put(dr.getSeries(), sdevs);
}
sdevs.add(dr);
}
for (Map.Entry<String, List<DevRev>> entry : revs.entrySet()) {
String series = entry.getKey();
List<DevRev> devices = entry.getValue();
System.out.println(series);
devices.sort(new Comparator<DevRev>() {
#Override
public int compare(DevRev o1, DevRev o2) {
return new Integer(o1.getModel()).compareTo(o2.getModel());
}
});
for (DevRev dr : devices) {
System.out.println("-> " + dr);
}
}
}
}
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 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)).
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 ;-)