Confusion on using instanceof along with other inherited data - java

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

Related

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

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
I started to learn java and i cant get past my problem with method getting default vaules from class. The code is about cars and garage. Everything works just as I intended with the execption of returning default values for Samochod s1 instead of the values that were set in the main function.
Main:
public static void main(String[] args) {
Samochod s1 = new Samochod("Fiat", "126p", 2, 650, 6.0);
Samochod s2 = new Samochod("Syrena", "105", 2, 800, 7.6);
Garaz g1 = new Garaz();
g1.setAdres( "ul. Garażowa 1" );
g1.setPojemnosc( 1 );
Garaz g2 = new Garaz("ul. Garażowa 2", 2);
g1.wprowadzSamochod(s1);
g1.wypiszInfo();
g1.wprowadzSamochod(s2);
g2.wprowadzSamochod(s2);
g2.wprowadzSamochod(s1);
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wyprowadzSamochod();
}
package Lab2_02;
public class Samochod {
private String marka;
private String model;
private int iloscDrzwi;
private int pojemnoscSilnika;
private double srednieSpalanie;
private static int iloscSamochodow = 0;
public String getMarka() {
return marka;
}
public String getModel() {
return model;
}
public int getIloscDrzwi() {
return iloscDrzwi;
}
public int getPojemnoscSilnika() {
return pojemnoscSilnika;
}
public double getSrednieSpalanie() {
return srednieSpalanie;
}
public void setMarka(String marka) {
this.marka = marka;
}
public void setModel(String model) {
this.model = model;
}
public void setIloscDrzwi(int iloscDrzwi) {
this.iloscDrzwi = iloscDrzwi;
}
public void setPojemnoscSilnika(int pojemnoscSilnika) {
this.pojemnoscSilnika = pojemnoscSilnika;
}
public void setSrednieSpalanie(double stednieSpalanie) {
this.srednieSpalanie = stednieSpalanie;
}
public Samochod() {
marka = "nieznany";
model = "nieznany";
iloscDrzwi = 0;
pojemnoscSilnika = 0;
srednieSpalanie = 0.0;
iloscSamochodow++;
}
public Samochod(String marka_, String model_, int iloscDrzwi_, int pojemnoscSilnika_, double srednieSpalanie_) {
marka = marka_;
model = model_;
iloscDrzwi = iloscDrzwi_;
pojemnoscSilnika = pojemnoscSilnika_;
srednieSpalanie = srednieSpalanie_;
iloscSamochodow++;
}
public double obliczSpalanie(double dlugoscTrasy) {
double spalanie = (srednieSpalanie * dlugoscTrasy)/100;
return spalanie;
}
public double obliczKosztPrzejazdu(double dlugoscTrasy, double cenaPaliwa) {
double kosztPrzejazdu = obliczSpalanie(dlugoscTrasy) * cenaPaliwa;
return kosztPrzejazdu;
}
public void wypiszInfo() {
System.out.println("Marka: " + marka);
System.out.println("Model: " + model);
System.out.println("Ilosc drzwi: " + iloscDrzwi);
System.out.println("Pojemnosc silnika: " + pojemnoscSilnika);
System.out.println("Srednie spalanie: " + srednieSpalanie);
}
public static void wypiszIloscSamochodow() {
System.out.println("Ilosc samochodow: " + iloscSamochodow);
}
}
package Lab2_02;
public class Garaz {
private String adres;
private int pojemnosc;
private int liczbaSamochodow = 0;
private Samochod [] samochody;
public String getAdres() {
return adres;
}
public int getPojemnosc() {
return pojemnosc;
}
public void setAdres(String adres) {
this.adres = adres;
}
public void setPojemnosc(int pojemnosc) {
this.pojemnosc = pojemnosc;
samochody = new Samochod[pojemnosc];
}
public Garaz() {
adres = "nieznany";
pojemnosc = 0;
samochody = null;
}
public Garaz(String adres_, int pojemnosc_) {
adres = adres_;
pojemnosc = pojemnosc_;
samochody = new Samochod[pojemnosc];
}
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod();
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
public void wyprowadzSamochod() {
if(liczbaSamochodow == 0) {
System.out.println("W garazu nie ma zadnego auta.");
}
else {
samochody [liczbaSamochodow-1] = null;
liczbaSamochodow--;
System.out.println("Samochod zostal wyprowadzony.");
}
}
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
}
}
}
So my problem is that instead of returning in console info about my car "Fiat", it say "nieznany" from default class. I know it is simple problem but i can't get past it for a few days. My problem is with this line:
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
Instead of showing this:
Samochod zostal wprowadzony.
Marka: nieznany
Model: nieznany
Ilosc drzwi: 0
Pojemnosc silnika: 0
Srednie spalanie: 0.0
I can't make it show this:
Marka: Fiat
Model: 126p
Ilosc drzwi: 2
Pojemnosc silnika: 650
Srednie spalanie: 6.0
In wprowadzSamochod(Samochod s) method you're creating a new Samochod instance, instead of using the one passed as parameter. Since you have a default constructor, you are always using it, setting information to default values:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod(); // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
How it should be:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = s; // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
Just a micro-suggestion: inside the exit condition of a for loop you can just use i < max, instead of i <= max-1 (e.g. in wypiszInfo()).

sorting an array of objects by some property without using collections that is doing manually

**In this i am trying to sort an array of objects by their id's whose age > 30 but compiler is giving error in searchVoteByAge function in while loop :
while((j>-1)&& (v[j].getVoterId() > key.getVoterId())) in this line **
error :Exception in thread "main"
java.lang.NullPointerException at algorithms.Dijstra_algo.searchVoterByAge(Dijstra_algo.java:77) at
algorithms.Dijstra_algo.main(Dijstra_algo.java:55)
import java.util.Scanner;
public class Demo
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Voter voter[]=new Voter[4];
for(int i=0;i<voter.length;i++){
int v_id=sc.nextInt();
sc.nextLine();
String v_nme=sc.next();
sc.nextLine();
int v_age=sc.nextInt();
sc.nextLine();
boolean is_vote_casted=sc.nextBoolean();
sc.nextLine();
String constituency=sc.next();
sc.nextLine();
voter[i]=new Voter();
voter[i].setVoterId(v_id);
voter[i].setVoterName(v_nme);
voter[i].setVoterAge(v_age);
voter[i].setVoteCasted(is_vote_casted);
voter[i].setConstituency(constituency);
}
String cons=sc.next();
int c=findTotal(voter,cons);
if(c>0)
System.out.println(c);
else
System.out.println("No votes Casted");
Voter v[]=searchVoterByAge(voter);
if(v.length > 0){
for(Voter obj: v){
System.out.println(obj.getVoterId());
}
}
else
System.out.println("No such voters");
}
private static Voter[] searchVoterByAge(Voter[] voters) {
Voter v[]=new Voter[voters.length];
int k=0,f=0;
for(Voter obj:voters) {
if(obj.getVoterAge()<30) {
v[k]=new Voter();
v[k++]=obj;
f=1;
}
}
for(int i=1;i<v.length;i++) {
Voter key=v[i];
int j=i-1;
while((j>-1)&& (v[j].getVoterId() > key.getVoterId())) {
v[j+1]=v[j];
j--;
}
v[j+1]=key;
}
if(f == 0) {
return new Voter[0];
}
else
return v;
}
static int findTotal(Voter voters[],String s){
int c=0;
for(Voter voter:voters){
if(voter.isVoteCasted() && voter.getConstituency().equals(s)){
c++;
}
}
return c;
}
}
** Voter Class**
public class Voter {
private int voterId;
private String voterName;
private int voterAge;
private String constituency;
private boolean isVoteCasted;
public int getVoterId() {
return voterId;
}
public void setVoterId(int voterId) {
this.voterId = voterId;
}
public String getVoterName() {
return voterName;
}
public void setVoterName(String voterName) {
this.voterName = voterName;
}
public int getVoterAge() {
return voterAge;
}
public void setVoterAge(int voterAge) {
this.voterAge = voterAge;
}
public String getConstituency() {
return constituency;
}
public void setConstituency(String constituency) {
this.constituency = constituency;
}
public boolean isVoteCasted() {
return isVoteCasted;
}
public void setVoteCasted(boolean isVoteCasted) {
this.isVoteCasted = isVoteCasted;
}
}

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?

Combination of counter and user input using Thread in Java?

I am a student and am studying threads recently. What I am trying to do is to implement MVC pattern that manages functionalities such as start counting, stop counting, reverse counting and etc...
My final goal is that, I need to get an user input whilst the counter is counting from 1, and if I input 2 (assuming that option 2 is stopping the counter), the counter should stops counting.
For example:
Counting...
1
2
3
(If I press 2 here)
Counter stopped running!
Because this is the homework from my college, I cannot upload here the code I implemented.
What I did was,
MVC pattern:
Controller class= gets model and view with Controller constructor. This class also provides service() method that uses switch case to make user to input to select the options to run the functionality for counting (eg) case1: startCounting() case2: stopCounting(), and etc...)
View class = provides options using System.out.println and displayMenu() function.
Model class = implements the functionalities such as startCounting(), stopCounting and etc...
I now need to add threads for this implementation in order to interact the user input with this counting process.
Can I please get any hints? For example, which class should I extend the Thread and in what way should I implement run() menthod?
Skeleton code:
CountController class
public class CounterController {
private Counter model;
private CounterView view;
public CounterController(Counter model, CounterView view) {
this.model = model;
this.view = view;
}
}
Model Class
public class Counter {
private int count = 0;
private boolean counting = false;
private Integer ceiling = null;
private Integer floor = null;
private boolean reverse = false;
public void startCounting() {
counting = true;
while (counting && checkLimits()) {
try {
Thread.sleep(1000);
count = reverse ? count - 1 : count + 1;
// You should replace this print with something observable so the View can handle it
System.err.println(count);
} catch (InterruptedException ignored) {}
}
}
public void stopCounting() {
counting = false;
}
public void setReverse(boolean reverse) {
this.reverse = reverse;
}
public void setCeiling(Integer ceiling) {
this.ceiling = ceiling;
}
public void setFloor(Integer floor) {
this.floor = floor;
}
public int getCount() {
return count;
}
public void resetCount() {
count = 0;
}
private boolean checkLimits() {
if (null != ceiling && count >= ceiling) {
return false;
}
if (null != floor && count <= floor) {
return false;
}
return true;
}
}
View Class
public class CounterView {
private Counter model;
public CounterView(Counter model) {
this.model = model;
}
public void launch() {
}
}
ViewUntil Class
class ViewUtils {
static int displayMenu(String header, String[] options, String prompt) {
System.out.println("\n" + header);
for (int i = 0; i < options.length; i++) {
System.out.println((i+1) + ". " + options[i]);
}
while (true) {
Integer response = getInt(prompt, true);
int selection = response != null ? response : -1;
if (selection > 0 && selection <= options.length) {
return selection;
} else {
System.out.println("Invalid menu selection");
}
}
}
static String getString(String prompt, boolean allowBlank) {
Scanner s = new Scanner(System.in);
String response;
do {
System.out.println(prompt);
response = s.nextLine();
if (!allowBlank && "".equals(response)) {
response = null;
System.out.println("Blank entry is not allowed here.");
}
} while (null == response);
return response;
}
static Integer getInt(String prompt, boolean allowBlank) {
int response;
do {
String str = getString(prompt, allowBlank);
if ("".equals(str)) {
return null;
}
try {
response = Integer.parseInt(str);
return response;
} catch (NumberFormatException e) {
System.out.println("Invalid input - number required");
}
} while (true);
}
static Boolean getBoolean(String prompt, boolean allowBlank) {
prompt = prompt + "(y/n) ";
Boolean response;
do {
String str = getString(prompt, allowBlank);
if ("".equals(str)) {
return null;
}
if ("y".equals(str.toLowerCase())) {
return true;
}
if ("n".equals((str.toLowerCase()))) {
return false;
}
System.out.println("Invalid input - must be y or n");
} while (true);
}
}
Main Class
public class MainDriver {
public static void main(String[] args) {
Counter model = new Counter();
CounterView view = new CounterView(model);
CounterController controller = new CounterController(model, view);
controller.service();
}
}
Using "volatile" to coerce the thread Counter to check for the newest setting values in memory and not in its "cache".
public class Counter {
private int count = 0;
private volatile boolean counting = false;
private volatile Integer ceiling = null;
private volatile Integer floor = null;
private boolean reverse = false;
...
}

Translating basic Actionscript game code into Java?

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

Categories

Resources