Java receipt program not displaying results - java

I have created a simple application that reads a series of products * quantity sold and generates a final order receipt that includes the sold item name, quantity and total for each item as well as the total for the whole receipt (including 6% sales tax). I feel that I accomplished this, except I cannot test the application as nothing is printing to the "receipt" AKA ContentPane. Below are the three classes I used.
PRODUCT class:
public class Product
{
private int coffeeQTY;
private int teaQTY;
private int bagelQTY;
private int muffinQTY;
private double tax;
private double total;
private double price;
private int productNOM;
public Product()
{
total=price=0.00;
productNOM=coffeeQTY=teaQTY=bagelQTY=muffinQTY=0;
}
//setters
public void setcoffeeQTY(int c)
{
coffeeQTY += c;
}
public void setteaQTY(int t)
{
teaQTY += t;
}
public void setbagelQTY(int b)
{
bagelQTY += b;
}
public void setmuffinQTY(int m)
{
muffinQTY += m;
}
//getters
public int getcoffeeQTY()
{
return coffeeQTY;
}
public int getteaQTY()
{
return teaQTY;
}
public int getbagelQTY()
{
return bagelQTY;
}
public int getmuffinQTY()
{
return muffinQTY;
}
public double getTAX()
{
return tax;
}
public double getTotal()
{
return total;
}
private double coffeePrice;
private double teaPrice;
private double bagelPrice;
private double muffinPrice;
public void inputOrder()
{
for(int i = 0; i <= 3; i++)
{
String order = JOptionPane.showInputDialog("Product 1: Coffee $3.65 "
+ "\nProduct 2: Tea $2.45 "
+ "\nProduct 3: Bagel $1.50 "
+ "\nProduct 4: Muffins $1.85 "
+ "\nEnter the number of the product you would like to order. Enter -1 when your order is complete: ");
productNOM = Integer.parseInt(order);
boolean done = false;
switch(productNOM)
{
case 1:
coffeePrice = 3.65;
String cQTY = JOptionPane.showInputDialog("Enter the quantity of Coffee you would like to order: ");
setcoffeeQTY(Integer.parseInt(cQTY));
break;
case 2:
teaPrice = 2.45;
String tQTY = JOptionPane.showInputDialog("Enter the quantity of Tea you would like to order: ");
setteaQTY(Integer.parseInt(tQTY));
break;
case 3:
bagelPrice = 1.50;
String bQTY = JOptionPane.showInputDialog("Enter the quantity of Bagels you would like to order: ");
setbagelQTY(Integer.parseInt(bQTY));
break;
case 4:
muffinPrice = 1.85;
String mQTY = JOptionPane.showInputDialog("Enter the quantity of the Muffins you would like to order: ");
setmuffinQTY(Integer.parseInt(mQTY));
break;
default:
done = true;
break;
}
total += coffeePrice * coffeeQTY + teaPrice * teaQTY + bagelPrice * bagelQTY + muffinPrice * muffinQTY;
if(!done)
{
tax = ((coffeePrice * coffeeQTY) * 0.06) + ((teaPrice * teaQTY) * 0.06) + ((bagelPrice * bagelQTY) * 0.06) + ((muffinPrice * muffinQTY) * 0.06);
total = (coffeePrice * coffeeQTY) + (teaPrice * teaQTY) + (bagelPrice * bagelQTY) + (muffinPrice * muffinQTY) + tax;
continue;
}
else
{
break;
}
}
}
public void draw(Graphics g)
{
g.drawString("Coffee $3.65 x" +getcoffeeQTY(), 25, 100);
g.drawString("Tes $2.45 x" +getteaQTY(), 25, 125);
g.drawString("Bagel $1.50 x" +getbagelQTY(), 25, 150);
g.drawString("Muffin $1.85 x" +getmuffinQTY(), 25, 175);
g.drawString("Tax(6%): " +getTAX(), 25, 225);
g.drawString("Total: " +getTotal(), 25, 250);
}
}
SALES class
public class Sales extends JComponent
{
private Product merch;
public Sales(Product m)
{
merch = m;
}
public void printSales(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
merch.draw(g2);
}
}
PRINTSALES class
public class PrintSales
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Product merch = new Product();
merch.inputOrder();
JFrame frame = new JFrame();
frame.setSize(500, 750);
frame.setTitle("Coffee Shop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.WHITE);
Sales store = new Sales(merch);
frame.add(store);
frame.setVisible(true);
}
}

I don't know if its related to the addition of the tax field, but it looks like the printSales(...) function is never called in, so nothing will be drawn.

Related

Creating a static average price method

Good afternoon, I can't write a static method to calculate the average price
Implement a static method to calculate the average price of goods in all baskets. It should calculate and return the ratio of the total cost of all baskets to the total number of all items.
Implement the static method for calculating the average cost of a basket (the ratio of the total cost of all baskets to the number of baskets).
I still have not been able to create static method data
public class Basket {
private static int count = 0;
private String items = "";
private int totalPrice = 0;
private double totalWeight = 0;
private int limit;
public static int allprice = 0;
public static int allcount = 0;
public static int averagebasket = 0;
public Basket() {
increaseCount(1);
items = "Список товаров:";
this.limit = 1000000;
}
public Basket(int limit) {
this();
this.limit = limit;
}
public Basket(String items, int totalPrice) {
this();
this.items = this.items + items;
this.totalPrice = totalPrice;
}
public static int getCount() {
return count;
}
public static int getAllTovar() {
return allcount;
}
public static int getAllPrice() {
return allprice;
}
public static int getAverageBasket() {
return averagebasket;
}
public double getTotalWeight(){
return totalWeight;
}
public static void increaseCount(int count) {
Basket.count = Basket.count + count;
}
public static void increaseTovar(int count) {
Basket.allcount = Basket.allcount + count;
}
public static void increasePrice(int totalPrice) {
Basket.allprice = Basket.allprice + totalPrice;
}
public static void average() {
Basket.averagebasket = allprice / allcount;
}
public void add(String name, int price, double weight) {
add(name, price, 1, weight);
}
public void add(String name, int price, int count, double weight) {
boolean error = false;
if (contains(name)) {
error = true;
}
if (totalPrice + count * price >= limit) {
error = true;
}
if (error) {
System.out.println("Error occured :(");
return;
}
increaseTovar(1);
items = items + "\n" + name + " - " +
count + " шт. - " + price + " Вес - " + totalWeight;
totalPrice = totalPrice + count * price;
totalWeight = totalWeight + weight;
Basket.allprice += price * count;
}
public void clear() {
items = "";
totalPrice = 0;
}
public int getTotalPrice() {
return totalPrice;
}
public boolean contains(String name) {
return items.contains(name);
}
public void print(String title) {
System.out.println(title);
if (items.isEmpty()) {
System.out.println("Корзина пуста");
} else {
System.out.println(items);
}
}
}
`
`public class Main {
public static void main(String[] args) {
Basket basket = new Basket();
basket.add("Milk", 40, 305.4);
basket.print("Milk");
//System.out.println(Basket.getCount());
Basket vasya = new Basket();
basket.add("bread", 60, 555);
System.out.println(Basket.getAllTovar());
System.out.println((Basket.getAllPrice()));
System.out.println(Basket.getAverageBasket());
}
}
Something like this?
public static double getAveragePrice() {
return (double) allPrice / allCount;
}
public static double getAverageBasket() {
return (double) allPrice / basketCount;
}

Check and retain the previous object instead of creating a new one

I am new to Java.
I created a banking system where user can pay their utility bills. I want to keep that status of the bills whether it is paid or not in Bills class. But whenever user wants to go to pay their bills and it creates a new object which vipes the previous data stored in that object. I want something to check if an object already exists it uses that but if it does not exists then create an object and use that. Please do let me know if it is possible.
Look at case 2 where it makes a new object everytime.
import java.util.Scanner;
import java.util.Random;
public class Main {
static boolean isAccount = false;
public static void main(String[] args) {
Menu menu = new Menu(isAccount);
menu.showMenu();
menu.take();
}
}
class Menu {
int option = 0;
boolean isAccount;
double money;
Scanner input = new Scanner(System.in);
public Menu(boolean isAccount) {
this.isAccount = isAccount;
}
public void showMenu() {
System.out.println("Choose your option: \n1. Create an Account\n2. Pay Bills\n3. Banking");
}
public void take() {
if (input.hasNextInt()) {
int opt = input.nextInt();
this.option = opt;
}
System.out.println("Option value: " + this.option);
navigate();
}
public void navigate() {
while (this.option != -1) {
switch (this.option) {
case 1:
if (!isAccount) {
Scanner nameInput = new Scanner(System.in);
System.out.print("Enter your name: ");
String name;
name = nameInput.next();
Random rand = new Random();
int id, number;
do {
number = rand.nextInt(99999);
id = number;
} while (number < 10000);
Scanner accountInput = new Scanner(System.in);
System.out.print("Do you want current account (true/false): ");
boolean isCurrent = accountInput.nextBoolean();
Account acc = new Account(name, id, isCurrent);
this.money = acc.getMoney();
acc.print();
isAccount = true;
} else {
System.out.println("You already have an account!");
}
break;
case 2:
if (isAccount) {
System.out.println("Money: " + this.money);
Bill bill = new Bill(this.money);
bill.showBills();
bill.selectBill();
this.money = bill.getMoney();
} else {
System.out.println("Please make an account before you pay the bill!");
showMenu();
take();
}
break;
case 3:
if (isAccount) {
Banking bank = new Banking(money);
bank.showMenu();
bank.takeOption();
this.money = bank.getMoney();
System.out.println("\nNew Bank Balance: " + this.money + "\n");
} else {
System.out.println("Please make an account before you do banking");
showMenu();
take();
}
}
this.showMenu();
this.take();
}
}
}
here's the bills class
import java.util.Scanner;
import java.util.Random;
class Bill {
class Paid {
boolean electricity, water, gas, internet = false;
}
int option;
double money;
Paid paidBills = new Paid();
public Bill(double money) {
this.money = money;
}
public void showBills () {
System.out.println("\nWhich bill do you want to pay?");
System.out.println("1. Electricity Bill\n2. Gas Bill\n3. Water Bill\n4. Internet Bill\n5. See Bills Status");
}
public void selectBill() {
Scanner input = new Scanner(System.in);
option = input.nextInt();
navigate(this.option);
}
public void navigate(int option) {
switch (option) {
case 1:
Electricity ebill = new Electricity(this.money);
double tempEBill = Math.floor(ebill.makeBill());
ebill.showBill(tempEBill);
this.money = ebill.pay(tempEBill);
ebill.receipt(tempEBill, this.money);
paidBills.electricity = true;
break;
case 2:
Gas gbill = new Gas(money);
double tempGBill = Math.floor(gbill.makeBill());
gbill.showBill(tempGBill);
this.money = gbill.pay(tempGBill);
gbill.receipt(tempGBill, this.money);
paidBills.gas = true;
break;
case 3:
Water wbill = new Water(money);
double tempWBill = Math.floor(wbill.makeBill());
wbill.showBill(tempWBill);
this.money = wbill.pay(tempWBill);
wbill.receipt(tempWBill, this.money);
paidBills.water = true;
break;
case 4:
Internet ibill = new Internet(money);
double tempIBill = Math.floor(ibill.makeBill());
ibill.showBill(tempIBill);
this.money = ibill.pay(tempIBill);
ibill.receipt(tempIBill, this.money);
paidBills.internet = true;
break;
case 5:
showPaidBills();
break;
}
}
public void showPaidBills() {
System.out.println("\nElectricty: " + paidBills.electricity + "\nWater: " + paidBills.water + "\nGas: " + paidBills.gas + "\nInternet: " + paidBills.internet + "\n");
}
public double getMoney() {
return this.money;
}
}
class Electricity {
double money;
static double bill;
public Electricity(double money) {
this.money = money;
}
public double makeBill() {
Random rand = new Random();
bill = rand.nextDouble() * 1000;
return bill;
}
public void showBill(double tempBill) {
System.out.println("\nElectricity Bill: " + tempBill);
}
public double pay(double tempBill) {
return money - tempBill;
}
public void receipt(double tempBill, double money) {
System.out.println("Bill paid amount = " + tempBill);
System.out.println("Remaining Amount in Bank = " + money + "\n");
}
}
class Water extends Electricity {
public Water(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nWater Bill: " + tempBill);
}
}
class Gas extends Electricity {
public Gas(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nGas Bill: " + tempBill);
}
}
class Internet extends Electricity {
public Internet(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nInternet Bill: " + tempBill);
}
}

In Java, How do I access a stored string object in an arrayLIst?

import java.util.ArrayList;
public class Portfolio {
ArrayList<String> myportfolio = new ArrayList<>();
int portfolioSize;
int holding;
public Portfolio(){
}
public void addStockHolding(StockHolding mystock){
myportfolio.add(String.valueOf(mystock));
}
public int getSize(){
portfolioSize = myportfolio.size();
return portfolioSize;
}
public boolean isInPortfolio(String ticker){
String temp = myportfolio.toString();
if (temp.contains(ticker)) return true;
else return false;
}
public void delaStock(int stockArray){
// String temp = myportfolio.toString();
//int tickerloc = temp.indexOf(ticker);
//int dot = temp.indexOf('.', tickerloc);
//String stocksumm = temp.substring(tickerloc, dot+3);
//myportfolio.remove(stocksumm);
}
public int getstockShares(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int colon = temp.indexOf(':', tickerloc);
int boughtStr = temp.indexOf("bought", tickerloc);
String stockShares = temp.substring(colon+1, boughtStr-1);
stockShares = stockShares.trim();
int sharesOwned = Integer.parseInt(stockShares);
return sharesOwned;
}
public double getstockPrice(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int dsign = temp.indexOf('$', tickerloc);
int dot = temp.indexOf('.', tickerloc);
String orgPrice = temp.substring(dsign+1, dot+3);
orgPrice = orgPrice.trim();
double purchasePrice = Double.parseDouble(orgPrice);
return purchasePrice;
}
public int stockLength(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int dot = temp.indexOf('.');
String stock = temp.substring(tickerloc, dot +2);
int stockloc = myportfolio.indexOf(stock);
return stockloc;
}
public String toString(){
String summary = (myportfolio.toString());
return summary;
}
}
public class StockHolding {
String ticker;
int numberShares;
double initialPrice;
double initialCost;
double currentValue;
double currentProfit;
double currentPrice;
public StockHolding(String ticker, int numberShares, double initialPrice){
this.ticker = ticker;
this.numberShares = numberShares;
this.initialPrice = initialPrice;
}
public String getTicker(String ticker){
return ticker;
}
double getInitialSharePrice(){
return initialPrice;
}
int getShares(){
return numberShares;
}
public double getCurrentSharePrice(){
return currentPrice;
}
public double getInitialCost(){
initialCost = numberShares * initialPrice;
return initialCost;
}
public double getCurrentValue(){
currentValue = numberShares * currentPrice ;
return currentValue;
}
public double getCurrentProfit(){
this.currentProfit = numberShares * (currentPrice - initialPrice);
return this.currentProfit;
}
public String toString(){
String summary = ("Stock " + ticker + ": " + numberShares + " bought at $ " + initialPrice + '\n');
return summary;
}
public void setCurrentSharePrice(double sharePrice){
currentPrice = sharePrice;
}
}
public class StockProject {
public static void main(String[] arg){
PortfolioAction transactions = new PortfolioAction();
}
}
public class Calculations {
private int haveShares;
private double pricePaid;
private String ticker;
private int num;
private int updShares;
private double price;
private double sale;
private Portfolio myportfolio;
private double priceDiff;
public Calculations(String ticker, int num, double price, Portfolio myportfolio){
this.ticker = ticker;
this.num = num;
this.price = price;
this.myportfolio = myportfolio;
}
public void setHaveShares() {
this.haveShares = myportfolio.getstockShares(ticker);
}
public int getHaveShares(){
return this.haveShares;
}
public void setPricePaid(){
pricePaid = myportfolio.getstockPrice(ticker);
}
public double getPricePaid(){
return this.pricePaid;
}
public void setSale(){
sale = num * price;
}
public double getSale(){
return sale;
}
public int getnumShares(){
return haveShares;
}
public void setUpdShares(){
this.updShares = haveShares - num;
}
public int getUpdShares(){
return this.updShares;
}
public void setPriceDiff(){
this.priceDiff = pricePaid - price;
}
public double getpriceDiff(){
this.priceDiff = pricePaid - price;
return this.priceDiff;
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
public class PortfolioAction {
private JLabel jlticker;
private JTextField jtenterTkr;
private JLabel jlnumShares;
private JTextField jtenterShares;
private JLabel jlPrice;
private JTextField jtenterPrice;
private JLabel jlLeft;
private JLabel jlCash;
private JLabel jlCashAmt;
private JLabel jlRight;
private JLabel butLeft;
private JButton jbsell;
private JButton jbbuy;
private JLabel butRight;
private JTextArea jtsummary;
Portfolio myportfolio = new Portfolio();
Account myaccount = new Account();
public PortfolioAction(){
Messages.getDisclaimer();
WidgetView wv = new WidgetView();
jlticker = new JLabel(" Stock Ticker "); //16
jtenterTkr = new JTextField(" "); //25
jlnumShares = new JLabel(" Number of Shares: "); //21
jtenterShares = new JTextField(" "); //25
jlPrice = new JLabel(" Price per Share: "); //21
jtenterPrice = new JTextField(" "); //25
jlLeft = new JLabel(" "); //65
jlCash = new JLabel(" Cash: $ "); //11
jlCashAmt = new JLabel(" 1000.00 " ); //11
jlRight = new JLabel(" "); //65
butLeft = new JLabel(" "); //60
jbsell = new JButton(" Sell ");
jbbuy = new JButton(" Buy ");
butRight = new JLabel(" ");
jtsummary = new JTextArea();
ButtonSell sellaction = new ButtonSell(jtenterTkr, jtenterShares, jtenterPrice, jlCashAmt, jtsummary);
ButtonBuy buyaction = new ButtonBuy(jtenterTkr, jtenterShares, jtenterPrice, jlCashAmt, jtsummary);
jbsell.addActionListener(sellaction);
jbbuy.addActionListener(buyaction);
wv.add(jlticker);
wv.add(jtenterTkr);
wv.add(jlnumShares);
wv.add(jtenterShares);
wv.add(jlPrice);
wv.add(jtenterPrice);
wv.add(jlLeft);
wv.add(jlCash);
wv.add(jlCashAmt);
wv.add(jlRight);
wv.add(butLeft);
wv.add(jbsell);
wv.add(jbbuy);
wv.add(butRight);
wv.add(jtsummary);
}
class ButtonSell extends WidgetViewActionEvent {
private JTextField enterTkr;
private JTextField enterShares;
private JTextField enterPrice;
private JLabel balance;
private JTextArea summary;
private boolean tkrLoc;
private int num;
private double price;
private String currBal;
private int previousShares;
private String ticker;
private double priceDiff;
private int haveShares;
private String salesummary;
public ButtonSell(JTextField jtenterTkr, JTextField jtenterShares, JTextField jtenterPrice, JLabel jlCashAmt, JTextArea jtSummary) {
enterTkr = jtenterTkr;
enterShares = jtenterShares;
enterPrice = jtenterPrice;
balance = jlCashAmt;
summary = jtsummary;
}
#Override
public void actionPerformed(ActionEvent e) {
this.ticker = enterTkr.getText();
this.ticker = ticker.trim();
try {
String numShares = enterShares.getText();
numShares = numShares.trim();
this.num = Integer.parseInt(numShares);
String getPrice = enterPrice.getText();
getPrice = getPrice.trim();
this.price = Double.parseDouble(getPrice);
String currBal = balance.getText();
this.currBal = currBal.trim();
}catch
(NumberFormatException ex) {
Messages.getNumErrMess();
}catch (NullPointerException ex){
Messages.getnotOwned();
}finally {
this.tkrLoc = myportfolio.isInPortfolio(ticker);
if (this.tkrLoc == false) {
Messages.getnotOwned();
} else{
Calculations sellStocks = new Calculations(ticker, num, price, myportfolio);
sellStocks.setHaveShares();
sellStocks.setPricePaid();
sellStocks.setUpdShares();
sellStocks.setPriceDiff();
sellStocks.setSale();
this.previousShares = sellStocks.getnumShares();
if(this.num > this.previousShares){
Messages.lowStockMsg();
balance.setText(currBal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
}else {
double sales = sellStocks.getSale();
myaccount.creditAccount(sales);
double newBal = myaccount.getBalance();
int holding = myportfolio.stockLength(ticker);
myportfolio.delaStock(holding);
int updShares = sellStocks.getUpdShares();
double pricePaid = sellStocks.getPricePaid();
StockHolding mystock = new StockHolding(ticker,updShares, pricePaid);
myportfolio.addStockHolding( mystock);
String bal = String.format("%.2f", newBal);
balance.setText(bal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
priceDiff = sellStocks.getpriceDiff();
haveShares = sellStocks.getHaveShares();
if (this.priceDiff < 0) {
double profit = priceDiff * haveShares* -1;
String hasProfit = String.format("%.2f" , profit);
salesummary = ("You made a profit of " + hasProfit);
} else if (this.priceDiff > 0) {
double loss = priceDiff * haveShares* -1;
String hasLoss = String.format("%.2f" , loss);
salesummary = ("You had a loss of " + hasLoss);
} else {
salesummary = "You have broke even.";
}
summary.setText(salesummary + '\n' + myportfolio.toString());
}
}
}
}
}
class ButtonBuy extends WidgetViewActionEvent {
private JTextField enterTkr;
private JTextField enterShares;
private JTextField enterPrice;
private JLabel balance;
private JTextArea summary;
public ButtonBuy(JTextField jtenterTkr, JTextField jtenterShares, JTextField jtenterPrice, JLabel jlCashAmt, JTextArea jtsummary) {
enterTkr = jtenterTkr;
enterShares = jtenterShares;
enterPrice = jtenterPrice;
balance = jlCashAmt;
summary = jtsummary;
}
#Override
public void actionPerformed(ActionEvent e) {
String ticker = enterTkr.getText();
ticker = ticker.trim();
try {
String numShares = enterShares.getText();
numShares = numShares.trim();
int num = Integer.parseInt(numShares);
String getPrice = enterPrice.getText();
getPrice = getPrice.trim();
double price = Double.parseDouble(getPrice);
double availCash = Double.parseDouble(balance.getText());
if ((price * num) > availCash) {
Messages.getMoneyMess();
}
else {
StockHolding mystock = new StockHolding(ticker, num, price);
myportfolio.addStockHolding(mystock);
double cost = mystock.getInitialCost();
myaccount.debitAccount(cost);
double newBal = myaccount.getBalance();
String bal = String.format("%.2f", newBal);
balance.setText(bal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
summary.setText(myportfolio.toString());
}
}
catch (NumberFormatException ex) {
Messages.getNumErrMess();
}
}
}
}
import javax.swing.JOptionPane;
public class Messages {
static String notEnuffFunds = "Transaction denied: Not enough Funds";
static String errNum = "Error: Number of Shares and Share price must be numbers only";
static String warn = "Warning";
static String noStock = "Stock not available to sell.";
static String disclaim = "Disclaimer";
static String disclosure = "This program is for entertainment purposes only. The account on this program does not represent" +
" any money in the real world nor does this predict any profit or loss on stocks you purchase in the real world.";
static String lowStock = "Not that meaning stock to sell";
public Messages(){
}
public static void getNumErrMess(){
JOptionPane.showMessageDialog(null, errNum, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getMoneyMess(){
JOptionPane.showMessageDialog(null, notEnuffFunds, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getnotOwned(){
JOptionPane.showMessageDialog(null, noStock, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getDisclaimer(){
JOptionPane.showMessageDialog(null, disclosure, disclaim, JOptionPane.INFORMATION_MESSAGE);
}
public static void lowStockMsg(){
JOptionPane.showMessageDialog(null, lowStock, warn, JOptionPane.WARNING_MESSAGE);
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A really simple class to display Swing widgets in a FlowLayout GUI.
* <p>
*
* #author parks
*/
public class WidgetView {
public static final int DEFAULT_X_SIZE = 600;
public static final int DEFAULT_Y_SIZE = 400;
private JFrame jframe;
private JPanel anchor;
private boolean userClicked = false;
private Lock lock;
private Condition waitingForUser;
private JComponent userInputComponent = null;
private ActionListener eventHandler;
/**
* Default constructor will display an empty JFrame that has a Flow layout
* JPanel as its content pane and initialize the frame to a default size.
*/
public WidgetView() {
this(DEFAULT_X_SIZE, DEFAULT_Y_SIZE);
}
/**
* Constructor will display an empty JFrame that has a Flow layout
* JPanel as its content pane and initialize the frame to a given size.
*/
public WidgetView(int pixelSizeInX, int pixelSizeInY) {
lock = new ReentrantLock();
waitingForUser = lock.newCondition();
// lambda expression requires Java 8
// eventHandler = e -> {
// if (e.getSource() != userInputComponent) {
// return;
// }
// lock.lock();
// userClicked = true;
// waitingForUser.signalAll();
// lock.unlock();
// };
//* java 7 solution
eventHandler = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() != userInputComponent) {
return;
}
lock.lock();
userClicked = true;
waitingForUser.signalAll();
lock.unlock();
}
};
jframe = new JFrame();
anchor = new JPanel();
jframe.setContentPane(anchor);
jframe.setSize(pixelSizeInX, pixelSizeInY);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
/**
* Add a Swing widget to the GUI.
*
* #param jcomp Swing widget (subclasses of JComponent--like JLabel and
* JTextField) to be added to the JFrame
*/
public void add(JComponent jcomp) {
anchor.add(jcomp);
jframe.setContentPane(anchor);
}
/**
* Add an Abstract Button (like a JButton) to the JFrame. Create an action
* listener to wait (suspend the caller) until it is clicked.
*
* #param absButton Button (like a JButton) to add to the JFrame
*/
public void addAndWait(AbstractButton absButton) {
userInputComponent = absButton;
absButton.addActionListener(eventHandler);
addWait(absButton);
}
/**
* Add a JTextField to the JFrame, and wait for the user to put the cursor
* in the field and click Enter. The caller is suspended until enter is
* clicked.
*
* #param jTextField Field to add to the JFrame
*/
public void addAndWait(JTextField jTextField) {
userInputComponent = jTextField;
jTextField.addActionListener(eventHandler);
addWait(jTextField);
}
private void addWait(JComponent jcomp) {
add(jcomp);
lock.lock();
try {
while (!userClicked) {
waitingForUser.await();
}
}
catch (InterruptedException e1) {
System.err.println("WidgetView reports that something really bad just happened");
e1.printStackTrace();
System.exit(0);
}
userClicked = false;
waitingForUser.signalAll();
lock.unlock();
}
}
import java.awt.event.ActionListener;
public abstract class WidgetViewActionEvent implements ActionListener {
}
public class Account {
double availableBalance = 1000.00;
public Account(){
}
public void debitAccount(double cost){
availableBalance -= cost;
}
public void creditAccount(double sale){
availableBalance += sale;
}
public double getBalance (){
return availableBalance;
}
}
I am working on a school project; a program that has the user enter a sticker, number of stocks and the price. then they have the option to buy and sell. The problem I am having is that say they bought 6 shares of IBM at 34.45 and want to sell 4 of them; I want to update the stock in the portfolio. I figured I would need to delete the original stock bought and put in the remaining stock as a new StockHolding. The problem is how do I find the index of the String in the arrayList of Portfolio to delete the old now out-dated StockHolding? The project has a Calculation class, a portfolioAction class, Messages class, and Account class, with the use of a WidgetView class that was supplied by the teacher. It is my first semester of Java. Thanks for any help.
updated: all the classes for the program are there now. The instructor wanted the inclusion of certain classes. We have not done hash maps and can only use the materials we have covered to this point. So I apologize.
: Output window for sell
I do not get any error messages; I am using IntelliJ IDEA. My problem is in the screenshot. It gives me the update stock but doesn't delete the old one. I have tried index of methods and am just stuck. But all the classes are here and it runs without error. Thank you again and sorry this is so lengthy.
To find the index of the string based on categories..
Try to use this below method:
private ArrayList<String> _categories;
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
To replace the old value in array list use set:
Instead of removing,
_categories.set( your_index, your_item )
Hope it helps.
your code is a bit long without specifications or sample output. But to find and change the stock you could use
myportfolio.set(indexOf(oldStock), newStock)

Java Suit Application using enums, methods and user input updated

I have got through all of this paper except the last part(Part 5) I have attached the picture of the paper for the part I am struggling with above.
When running my application tester, when I press 3, nothing happens. Does anyone know why? the code of my classes is below. NOTE: the updateBrand() method which is called in the tester in the makeChangeToSuit method is in the morningSuit and suit classes.
I would appreciate any help on this matter.
package SuitProg;
import java.util.Scanner;
public abstract class Suit {
//instance variables
private String Colour;
private double dailyCost;
private int trouserLength;
private int jacketChestSize;
private boolean available;
protected double totalPrice;
//constructor
public Suit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available) {
super();
Colour = colour;
this.dailyCost = dailyCost;
this.trouserLength = trouserLength;
this.jacketChestSize = jacketChestSize;
this.available = available;
this.totalPrice = totalPrice;
}
//accessors & mutators
public String getColour() {
return Colour;
}
public double getDailyCost() {
return dailyCost;
}
public int getTrouserLength() {
return trouserLength;
}
public int getJacketChestSize() {
return jacketChestSize;
}
public boolean getAvailability() {
return available;
}
public double getTotalPrice() {
return totalPrice;
}
public void setDailyCost(double dailyCost) {
this.dailyCost = dailyCost;
}
public void setTrouserLength(int trouserLength) {
this.trouserLength = trouserLength;
}
public void setJacketChestSize(int jacketChestSize) {
this.jacketChestSize = jacketChestSize;
}
public void setAvailability(boolean available) {
this.available = available;
}
//methods
public String toString() {
return " Suit [ Colour: " + getColour() + ", Daily Cost: " + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability();
}
public void calcTotalPrice (int numDaysHired) {
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
}
public String printDailyCost() {
getDailyCost();
return "£" + String.format("%.2f", getDailyCost());
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(null);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
import java.util.Scanner;
public class MorningSuit extends Suit implements Brandable {
//instance variables
private boolean boutonniere;
private boolean topHat;
public Brand brand;
//constructor
public MorningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean boutonniere, boolean topHat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.boutonniere = boutonniere;
this.topHat = topHat;
}
//accessors & mutators
public boolean getBout() {
return boutonniere;
}
public boolean getTopHat() {
return topHat;
}
public void setBout(boolean boutonniere) {
this.boutonniere = boutonniere;
}
public void setTopHat(boolean topHat) {
this.topHat = topHat;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
//methods
public String toString() {
return "Morning Suit [ Boutonniere " + getBout() + " TopHat " + getTopHat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice(int numDaysHired) {
if (getBout()) {
totalPrice = totalPrice + 3;
}
if (getTopHat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (numDaysHired * getDailyCost());
System.out.println("The morning suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Morning Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(input);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
public enum Brand {
Highstreet,TedBaker,FrenchConnection
}
package SuitProg;
public interface Brandable {
public String getBrand();
}
package SuitProg;
import java.util.Scanner;
public class EveningSuit extends Suit implements Brandable {
//variables
private boolean cufflinks;
private boolean waistcoat;
public Brand brand;
public EveningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean cufflinks, boolean waistcoat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.cufflinks = cufflinks;
this.waistcoat = waistcoat;
this.brand = Brand.Highstreet;
}
//accessors & mutators
public boolean getCuffs() {
return cufflinks;
}
public boolean getWaistcoat() {
return waistcoat;
}
public void setCuffs(boolean cufflinks) {
this.cufflinks = cufflinks;
}
public void setWaistcoat(boolean waistcoat) {
this.waistcoat = waistcoat;
}
//methods
public String toString() {
return "Evening Suit [ Cufflinks " + getCuffs() + " Waistcoat " + getWaistcoat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice (int numDaysHired) {
if (getCuffs()) {
totalPrice = totalPrice + 5;
}
if (getWaistcoat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
System.out.println("The evening suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Evening Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
System.out.println("You can not change the brand name of an evening suit.");
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
}
package SuitProg;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester05 {
public static void main(String[] args) {
//create arrayList of suits
ArrayList<Suit> suits = new ArrayList<Suit>();
//create morningSuit object
MorningSuit MorningSuit1 = new MorningSuit("Black", 80.00, 32, 36, true, true, false);
MorningSuit1.setBrand(Brand.FrenchConnection);
//create evening suit
EveningSuit EveningSuit1 = new EveningSuit("White", 70.25, 34, 36, true, true, true);
//add suits to arrayList
suits.add(MorningSuit1);
suits.add(EveningSuit1);
//print all details of arrayList
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
System.out.println(MorningSuit1.getBrand());
System.out.println(EveningSuit1.getBrand());
printMenu(suits);
}
public static void printMenu(ArrayList<Suit> suits) {
Scanner input = new Scanner(System.in);
System.out.println("----------------Suit Hire-----------------");
System.out.println("What would you like to do?");
System.out.println("\n1)Display all suits\n2)Display available suits\n3)Change Suit brand\n4)Finished");
System.out.println("Please select an option: ");
int selection = input.nextInt();
if (selection == 1) {
displayAllSuits(suits);
} else
if (selection == 2) {
displayAllSuits(suits);
}
else
if (selection ==3) {
makeChangeToSuits(suits, input);
}
else
if (selection ==4) {
System.out.println("You are now exitting the system.");
System.exit(0);
}
}
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (int i = 0; i > suits.size(); i ++) {
suits.get(i).updateBrand(input);
}
}
public static void displayAllSuits(ArrayList<Suit> suits) {
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
}
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (int i = 0; i > suits.size(); i++) {
if (suits.get(i).getAvailability()) {
System.out.println(suits.get(i).toString());
}
}
}
}
The problem is in your makeChangeToSuits method when you iterate the list. It should look like:
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (Suit suit : suits) {
suit.updateBrand(input);
}
}
Also, your displayAvailableSuits method should look like:
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (Suit suit : suits) {
if (suit.getAvailability()) {
System.out.println(suit.toString());
}
}
}

setting up win in the end of the game

I have a problem when i compile my code. I want to make my "Win" image to pop up when the score reaches 500 or over, but i get this error:
"incompatible types: int cannot be converted to score"
The problem is under my "private void LevelUp"()"
Here is my code:
import greenfoot.*;
/**
* Write a description of class MinionWorld here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class MinionWorld extends World
{
private long startMillis = 0;
private int numFrames = 0;
private final int groundHeight;
public static final double MAX_FORCE = 11;
public static final double MIN_FORCE = 7;
public static final double GRAVITY = 0.15;
public static final int LOWEST_ANGLE = 30;
private Player[] players;
private int curPlayer;
private int turnCountdown;
private int value;
Score score;
Banan Banan;
private int time, target;
public static int poin, level;
/**
* Constructor for objects of class Banana.
*
*/
public MinionWorld()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(800, 500, 1, false);
groundHeight = 440;
players = new Player[] {new Minion()};
int x = getWidth() / 2;
for (Player p : players)
{
addObject(p, x, groundHeight);
}
curPlayer = 0;
turnCountdown = 10;
time = 1800;
poin = 0;
level = 1;
target = 150;
Greenfoot.setSpeed(50);
prepare();
}
private void showTime()
{
showText("Time: " + time/60, 700, 20);
}
private void showTarget()
{
showText("Target: "+target, 714, 50);
}
private void showLevel()
{
showText("Level: "+level, 50, 20);
}
private void countTime()
{
showTime();
if(time>0)
{
time--;
}
if (time == 0)
{
LevelUp();
}
}
private void lvup()
{
LvlUp LvlUp = new LvlUp();
addObject(LvlUp,400,250);
Greenfoot.delay(200);
removeObject(LvlUp);
}
private void win()
{
Win Win = new Win();
addObject(new Win(),400,250);
Greenfoot.delay(200);
}
public void started()
{
numFrames = 0;
startMillis = System.currentTimeMillis();
}
private double t;
public void act()
{
numFrames += 1;
t = getTimePerFrame();
if (turnCountdown > 0)
{
turnCountdown -= 1;
if (turnCountdown == 0)
{
players[curPlayer].startTurn();
}
}
countTime();
showTarget();
showLevel();
}
public void changeScore(int nilai)
{
if(score!=null)
{
score.setScore(nilai);
}
}
public double getTimePerFrame()
{
return (double)(System.currentTimeMillis() - startMillis) / (1000.0 * (double)(numFrames));
}
public boolean hitsGround(double startX, double startY, double endX, double endY)
{
return endY > groundHeight;
}
public void landed()
{
curPlayer = (curPlayer + 1) % players.length;
turnCountdown = 10;
}
private void LevelUp()
{
{
if(poin>=target)
{
level++;
if (level==2)
{
lvup();
time=1800;
target=350;
}
if (level==3)
{
lvup();
time=1800;
target=500;
}
}
else
{
if (score = 500)
{
Greenfoot.stop();
addObject(new Win(), 400,200);
}
else
{
addObject(new GameOver(),400,200);
addObject(new TryAgain(),360, 320);
addObject(new Exit(),460,320);
}
}
}
}
/**
* Prepare the world for the start of the program. That is: create the initial
* objects and add them to the world.
*/
private void prepare()
{
Menu Menu = new Menu();
Greenfoot.setWorld(Menu);
score = new Score();
Minion Minion = new Minion();
addObject(Minion, 373, 435);
Minion.setLocation(461, 400);
removeObject(Minion);
Evil1 evil1 = new Evil1();
addObject(evil1, 697, 212);
evil1.setLocation(577, 223);
Evil2 evil2 = new Evil2();
addObject(evil2, 259, 58);
evil2.setLocation(695, 63);
evil2.setLocation(693, 53);
Evil3 evil3 = new Evil3();
addObject(evil3, 742, 322);
evil3.setLocation(575, 321);
evil3.setLocation(323, 305);
evil3.setLocation(573, 319);
Evil4 evil4 = new Evil4();
addObject(evil4, 92, 117);
evil4.setLocation(92, 111);
Score score = new Score();
addObject(score, (697), 168);
score.setLocation(757, 247);
score.setLocation(561, 163);
score.setLocation(463, 124);
}
}
Here is my code for my Score class:
import greenfoot.*;
public class Score extends Actor
{
/**
* Act - do whatever the Score wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public Score(){
GreenfootImage gfi = new GreenfootImage(200,200);
gfi.setColor(java.awt.Color.white);
gfi.setFont(new java.awt.Font("Las Vegas",java.awt.Font.PLAIN, 36));
gfi.drawString("0", 30, 30);
setImage(gfi);
}
public void setScore(int score)
{
GreenfootImage gfi = getImage();
gfi.clear();
gfi.drawString(score + "", 30,30);
setImage(gfi);
}
//just a little settlement
public void act()
{
if(MinionWorld.poin>9)
{
setLocation(445, getY());
}
}
}
Code for "move" class:
import greenfoot.*;
/**
* Write a description of class Move here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Move extends Actor
{
int q = 0;
private int Evil = 0;
/**
* Act - do whatever the Fly wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
}
public void flyy()
{
if (getX() == 0 || getX() == 799)
{
setLocation(getX(), 50+Greenfoot.getRandomNumber(320));
turn(180);
this.getImage().mirrorVertically();
q++;
}
}
public void right()
{
move(3/2);
}
public void left()
{
move(-3/2);
}
public void touch1()
{
if(isTouching(Banan.class))
{
MinionWorld MinionWorld = (MinionWorld) getWorld();
MinionWorld.poin = MinionWorld.poin + 10;
MinionWorld.changeScore(MinionWorld.poin);
removeTouching(Evil1.class);
setLocation(799, 50+Greenfoot.getRandomNumber(320));
left();
}
}
public void touch2()
{
if(isTouching(Banan.class))
{
MinionWorld MinionWorld = (MinionWorld) getWorld();
MinionWorld.poin = MinionWorld.poin + 10;
MinionWorld.changeScore(MinionWorld.poin);
removeTouching(Evil2.class);
setLocation(0, 50+Greenfoot.getRandomNumber(320));
right();
}
}
public void touch3()
{
if(isTouching(Banan.class))
{
MinionWorld MinionWorld = (MinionWorld) getWorld();
MinionWorld.poin = MinionWorld.poin + 10;
MinionWorld.changeScore(MinionWorld.poin);
removeTouching(Evil3.class);
setLocation(799, 50+Greenfoot.getRandomNumber(320));
left();
}
}
public void touch4()
{
if(isTouching(Banan.class))
{
MinionWorld MinionWorld = (MinionWorld) getWorld();
MinionWorld.poin = MinionWorld.poin + 10;
MinionWorld.changeScore(MinionWorld.poin);
removeTouching(Evil4.class);
setLocation(0, 50+Greenfoot.getRandomNumber(320));
right();
}
}
public void nulled2()
{
if (getWorld().getObjects(Evil2.class).isEmpty())
{
getWorld().addObject(new Evil2(), 0, 50+Greenfoot.getRandomNumber(320));
right();
}
}
public void nulled4()
{
if (getWorld().getObjects(Evil4.class).isEmpty())
{
getWorld().addObject(new Evil4(), 0, 50+Greenfoot.getRandomNumber(320));
right();
}
}
public void flyback1()
{
if(getX()<-15)
{
setLocation(800, 50+Greenfoot.getRandomNumber(320));
}
if(getX()>815)
{
setLocation(799, 50+Greenfoot.getRandomNumber(320));
turn(180);
this.getImage().mirrorVertically();
}
}
public void flyback2()
{
if(getX()<-35)
{
setLocation(0, 50+Greenfoot.getRandomNumber(320));
turn(180);
this.getImage().mirrorVertically();
}
if(getX()>834)
{
setLocation(0, 50+Greenfoot.getRandomNumber(320));
}
}
}
This is a little bit too long for a comment so I'll post it here.
You are most likely missing the following:
A field in your Score class.
A getter for that field`.
Fixing if (score = 500) and changing it to if (score.getScore() == 500).
So basically:
public class Score extends Actor {
private int score;
public void setScore(int score) {
this.score = score;
...
}
public int getScore() {
return this.score;
}
}
You are missing a score field. Your class should be like this:
public class Score extends Actor
{
private int score;
public int getScore(){
return score;
}
/**
* Act - do whatever the Score wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public Score(){
GreenfootImage gfi = new GreenfootImage(200,200);
gfi.setColor(java.awt.Color.white);
gfi.setFont(new java.awt.Font("Las Vegas",java.awt.Font.PLAIN, 36));
gfi.drawString("0", 30, 30);
setImage(gfi);
}
public void setScore(int score)
{
GreenfootImage gfi = getImage();
gfi.clear();
this.score += score;
gfi.drawString(this.score + "", 30,30);
setImage(gfi);
}
//just a little settlement
public void act()
{
if(MinionWorld.poin>9)
{
setLocation(445, getY());
}
}
}
Then your if should be:
if(score.getScore() == 500){
//doStuff
}

Categories