Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have to use these two methods in my program but I have no idea what they do because my program works the way I want it to without these and when I put them in my code it doesn't make a difference in the output or anything.
public double getPurchase() {
return purchase;
}
public int getItems() {
return numItems;
}
Here is the rest of my code:
public class GroceryListIU extends javax.swing.JFrame {
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
public double itemPrice;
public final double SALES_TAX = 0.065;
public double totalPrice;
public double tax;
public double purchase;
public int numItems;
/**
* Creates new form GroceryListIU
*/
public GroceryListIU() {
initComponents();
//delcares purchase and numItems and resets them to 0
purchase = 0;
numItems = 0;
}
//set method to add item price
public void recordPurchase(double itemPrice) {
purchase = purchase + itemPrice;
numItems++;
}
public double getPurchase() {
return purchase;
}
public int getItems() {
return numItems;
}
private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {
//clicking exit ends the program
System.exit(0);
}
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
//When the user clicks "reset" all variables are set to blank or 0
txtItemPrice.setText("");
txtSubTotal.setText("");
txtNumberOfItems.setText("");
txtSalesTax.setText("");
txtTotalPrice.setText("");
numItems = 0;
purchase = 0;
}
private void btnCheckoutActionPerformed(java.awt.event.ActionEvent evt) {
boolean keepShopping = true;
JFrame frame = new JFrame();
while (keepShopping) {
try {
//When the user clicks "checkout" a input dialog will appear to enter the item price
String newItemPrice = JOptionPane.showInputDialog(frame,
"Enter Item Price",
"Enter Price",
JOptionPane.PLAIN_MESSAGE);
//if the user clicks cancel or clicks OK and left the text field blank, calculations will be made
if ((newItemPrice != null) && (newItemPrice.length() > 0)) {
//parse the double item price
itemPrice = Double.parseDouble(newItemPrice);
//takes itemPrice and plugs it into recordPurchase method
recordPurchase(itemPrice);
//adds 1 to txtNumberOfItems each time the user enters a number until it ends
txtNumberOfItems.setText((numItems) + "");
//adds item price to the txtItemPrice text field
txtItemPrice.setText(defaultFormat.format(itemPrice));
//adds the sub total to the txtSubTotal text field
txtSubTotal.setText(defaultFormat.format(purchase));
} else {
//when the user clicks ok when blank or cancel the program does the rest of the calculations
keepShopping = false;
//tax is 6.5%, you would multiply that by the purchase total
tax = SALES_TAX * purchase;
//sets "tax" in the txtSalesTax text field
txtSalesTax.setText(defaultFormat.format(tax));
//the total price is tax plus the sub total
totalPrice = tax + purchase;
//add the total price to the totalPrice text field
txtTotalPrice.setText(defaultFormat.format(totalPrice));
}
} catch (NumberFormatException e) { //if the user enters string data, an error will appear
JOptionPane.showMessageDialog(frame,
"You must enter positive numerical data!",
"Bad Data!",
JOptionPane.ERROR_MESSAGE);
}
}
}
How do I use them in my program?
Therese are getters. You might have them on your program, but you never used them.
Note that they are public, while the variables they return should have been private. You're breaking encapsulation by exposing your data members.
Consider this class:
public class MyClass {
private int myPrivateInt;
private String myPrivateString;
public int getInt() {
return myPrivateInt;
}
public String getString() {
return myPrivateString;
}
}
Since myPricateInt and myPrivateString are private, you can't access them from outside, that's why I need a getter method to get these variables.
They are getters
The point of getters and setters is that only they are meant to be used to access the private varialble, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.
Short and sweet advantages are
For Re-usability.
To perform Validation in later stages of programming.
Getter and setter methods are public interfaces to access private
class members
As per ur Q
public double getPurchase() {
return purchase;
}
public int getItems() {
return numItems;
}
purchase and numItems are private, so u need getters
This is encapsulation.
If you have getters like these, then private access modifiers on your fields would make them more meaningful.
private double purchase;
private int numItems;
Silly Question.
Those are getter methods for the variables purchase and nemItems, which are private .
Accessors and Mutators in Java. Does it ring a bell.
They are set and get methods. Public double getPurchase() returns the purchase variable from the class and public int getItems() returns the numItems variable. The reason it doesn't affect your code when you remove them is because you are accessing those variables directly because they are public. You would have to use those methods if you had your variables set to private.
Related
I'm doing a menu-based system where it will calculate my monthly rent using specific variables (double - monthlyRent, double waterBill, double energyBill etc.)
The program starts with prompting the user to select an option:
(1) create a budget invoice (this is where a projected monthly rent invoice will be calculated)
When the user selects this option I want to use an ArrayList to store the monthly rent invoices. I have a variable where the user can put an InvoiceID to search an already existing monthly rent invoices or delete etc.
My problem is how to use specific indexes in my ArrayList to input monthly rent, water bill and so forth and the next index will be a different monthly rent, waterbill, energy bill etc.). In a general sense, store multiple variable and variable types within 1 index of the ArrayList.
My ArrayList is in its own class, different from the function that I want to create to generate monthly budget invoices. My problem is how to prompt user input for each rent variable and store all of those inputs in its proper index of the ArrayList where that specific monthly invoice will be stored. The variables are double, string and int types.
import java.util.ArrayList;
public class InvoicerHub {
static ArrayList<Object> invoicerSys = new ArrayList<Object>();
}
import java.util.ArrayList;
import java.util.Scanner;
public class BudgetInvoice extends InvoicerHub {
protected double monthlyRent ;
protected double waterBill;
protected double energyBill;
protected double carRent;
protected double internetRent;
protected String invoiceID;
public int counter = 0;
static Scanner myScan= new Scanner(System.in);
public double getMonthlyRent() {
return monthlyRent;
}
public void setMonthlyRent(double monthlyRent) {
this.monthlyRent = monthlyRent;
}
public double getWaterBill() {
return waterBill;
}
public void setWaterBill(double waterBill) {
this.waterBill = waterBill;
}
public double getEnergyBill() {
return energyBill;
}
public void setEnergyBill(double energyBill) {
this.energyBill = energyBill;
}
public double getCarRent() {
return carRent;
}
public void setCarRent(double carRent) {
this.carRent = carRent;
}
public double getInternetRent() {
return internetRent;
}
public void setInternetRent(double internetRent) {
this.internetRent = internetRent;
}
public String getInvoiceID() {
return invoiceID;
}
public void setInvoiceID(String invoiceID) {
this.invoiceID = invoiceID;
}
public static InvoicerHub getInvoice()
{
invoicerSys = new ArrayList<>();
if (invoicerSys.isEmpty()== true)
{
} // This is where I'm stuck.
I was given a task to create a java program that use this 3 classes. Main class, Menu class and Coffee Class. Now i need to pass value from menu class to coffee class. But the problem is i dont exactly know how to do it since im still new with java.
CoffType pass the value to CoffeeName.
NumBag pass the value to NumberOfBag.
This is menu class(programmer defined class 1)
import java.util.*;
public class Menu {
Scanner scan = new Scanner(System.in);
public String coffType;
public int numBag;
public void setCoffType() {
System.out.println("\t\tChoose Your Coffee");
System.out.println("\n[1] Arabica\tRM12.50 per bag");
System.out.println("\n[2] Robusta\tRM15.00 per bag");
coffType = scan.nextLine();
}
public void setNumBag() {
System.out.println("Enter amount you wish to buy");
numBag = scan.nextInt();
}
}
Coffee Class(programmer defined class 2)
public class Coffee{
private String coffeeName;
private double coffeePrice;
private double amountPay;
private int numberOfBag;
private double discount;
public Coffee() { // constructor
coffeeName = "unknown";
coffeePrice = 0.00;
amountPay = 0.00;
numberOfBag = 0;
discount = 0.00;
}
public double getCoffeePrice() {
if(coffeeName.equalsIgnoreCase("arabica")) {
coffeePrice = 12.50 * numberOfBag;
}
else if(coffeeName.equalsIgnoreCase("robusta")) {
coffeePrice = 15.00 * numberOfBag;
}
System.out.println("Price RM: " +coffeePrice);
return coffeePrice;
}
public double getDiscount() {
if(numberOfBag>0 && numberOfBag<=50) {
discount = coffeePrice*0;
}
if(numberOfBag>50 && numberOfBag<=100) {
discount = coffeePrice*0.10;
}
if(numberOfBag>100 && numberOfBag<=150) {
discount = coffeePrice*0.15;
}
if(numberOfBag>150 && numberOfBag<=200) {
discount = coffeePrice*0.20;
}
if(numberOfBag>200) {
discount = coffeePrice*0.25;
}
System.out.println("Discount RM: " +discount);
return discount;
}
public double getAmountPay() {
amountPay = coffeePrice - discount;
System.out.println("\nTotal Need To Pay RM: " +amountPay);
return amountPay;
}
}
I want to pass coffType to coffeeName and numbag to numberOfBag. How can i change these values?
In CoffeClass create a constructor that receives the parameter that you want to set:
public Coffee(String coffeeName, double amountPay, int numberOfBag) {
this.coffeeName = coffeeName;
this.amountPay = amountPay;
this.numberOfBag = numberOfBag;
}
In MenuClass you will instantiate the object Coffe with the selected values by the user:
Coffe coffeOne = new Coffe(coffeName, amoutPay, numBag);
In the same class use the object to get the discount:
double discountCoffeOne = coffeOne.getDiscount();
You're done.
You use the CoffeClas as a model to an object with the values that you want. That way you can have a lot of different coffe just instantiating another Coffe with another name and using it.
When needed you should use getters and setters to change the attributes of an object, when needed means you should not create them when the values are not supposed to change or the other classes should not have permission to change these attributes.
public setCoffeeName(String coffeeName){
this.coffeeName = coffeName
};
public getCoffeeName(){
return coffeName;
}
;)
Oh, and just like azro said:
"Please follow conventions, and start naming attributs/variables with lowercase"
Here, inorder to pass the value of CoffType to CoffeeName and NumBag to NumberOfBag we can either use a parameterized constructor or setters. Both ways we can pass the value from Menu class to Coffee class.
Using parameterized constructor
create parameterized constructor in the Coffee class and instantiate the Coffee class from the Menu class.
Setter
create 2 setters to set each of NumberOfBag and CoffeName in the Coffee class and set the value by instatiating Coffee class and setting the value to both.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I am very new to Java... been at it for about 4 weeks... be gentle.
I am trying to get my takeItem method (below) to pass the itemName variable back to my Player Class so I can add an item from my current room to my player. I get the compiler error: Constructor Item in class Item cannot be applied to given types..
my end goal is to get the player class to hold the object after removing it from the room.
takeItem Method:
private void takeItem(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Take what?");
System.out.println();
return;
}
String itemName = command.getSecondWord();
Item theItem;
// Try to take an item.
theItem = new Item(player.getCurrentRoom().removeItem(itemName));
if (theItem == null)
{
System.out.println("There is no item!");
}
else
{
player.addItem(theItem);
player.getItemsCarried();//print item info
}
Player Class:
//above code omitted//
public void setCurrentRoom(Room room)
{
currentRoom = room;
}
public Room getCurrentRoom()
{
return currentRoom;
}
//code below omitted//
public void addItem (Item thingy)
{
items.put(thingy.getName(), thingy);
}
//code below omitted//
Item Class:
public class Item
{
// instance variables - replace the example below with your own
private String name;
private String description;
private int weight;
/**
* Constructor for objects of class Item
*/
public Item(String n, String d, int w)
{
name = n;
description = d;
weight = w;
}
//code below omitted//
Room Class:
public class Room
{
private String description;
private HashMap <String, Room> exits;
private HashMap <String, Item> items;
//some code below omitted//
public Room (String description)
{
this.description = description;
exits = new HashMap<>();
items = new HashMap<>();
}
public void addItem (Item thingy)
{
items.put(thingy.getName(), thingy);
}
public String removeItem(String thingy)
{
items.remove(thingy);
return thingy;
}
//code below omitted
Your constructor in the Item class takes two String parameters and one int, but you are trying to create a new Item by passing in only one String (whatever is returned by the removeItem() method). You can either change the removeItem() method so that it returns the Item that is removed, in which case you should change
theItem = new Item(player.getCurrentRoom().removeItem(itemName));
to
theItem = player.getCurrentRoom().removeItem(itemName);
or you can create a new Item with the necessary parameters.
I'm just starting my first real project in Java so I'm still understanding the basics so apologies for this.
I'm working out the price * quantity then giving the total amount to each individual product, this will then have to be repeated for all my products as part of the order process. So i want to find the best way so i can repeat it.
Here is the working code I have:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
double priceA = 20.00;/*fixed price*/
String strA = txtbxCaseA.getText();/*gets amount from textbox*/
int numA = Integer.parseInt(strA);/*parse to int */
double casetotalA = (priceA * numA);/*sum*/
String caseAtotal = String.valueOf(casetotalA);/*to string */
double priceB = 25.00;
String strB = txtbxCaseB.getText();
int numB= Integer.parseInt(strB);
double casetotalB = (priceB * numB);
String caseBtotal = String.valueOf(casetotalB);
double priceC = 30.00;
String strC = txtbxCaseC.getText();
int numC = Integer.parseInt(strC);
double casetotalC = (priceC * numC);
String caseCtotal = String.valueOf(casetotalC);
ArrayList caselist = new ArrayList();
caselist.add("Case A Total - £" + caseAtotal);
caselist.add("Case B Total - £" + caseBtotal);
caselist.add("Case C Total - £" + caseCtotal);
DefaultListModel myModel = new DefaultListModel ();
for(int i = 0; i < caselist.size(); i++){
jTextArea3.append((String)caselist.get(i) + ('\n'));
myModel.addElement(caselist.get(i) + ",");
/*
- save arraylist to a gobal varible for cart processing
- move to next panel (page) along
*/
}
}
My question is, is this method good practice, and also is their a better method (maybe shorter) that i can repeat for each of my 50 products as this seems a little inefficient but it works.
Any suggestions or comments would be greatly appreciated.
is their a better method (maybe shorter) that i can repeat for each
of my 50 products
Why not store your products in a collection (a List) such that you can iterate through each one and total as you go ? If you have a Product object you can then assign a price to each as a member and iterate through totalling as you go.
for (Product p : listOfProducts) {
sum = sum + p.price * quantity;
}
Note that I would pull the above out into a price calculator or similar such that you can run and test (via a unit test framework such as JUnit) separately from the GUI Swing code.
One thing that can be done is that you can use an array of TextBox and create a function that calculates the value and inserts in the Arraylist and this function is called in a loop inside the button event handler method. Also try to use ArrayList<String> instead of ArrayList. That ensures stronger type checking.
Some tips for improving your overall project, making it easier for yourself. Some of these tips have been posted already in other answers.
The basic principle is (like Ceiling Gecko commented): If you see yourself repeating code, make a generic way to code it once and reuse that code for each of the repetitions.
Use a Product class
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
This you will populate, for every product you have, at the very start of your program and store it either in an array or a List
List<Product> productList = new ArrayList<Product>();
productList.add(new Product("Milk", 10.00));
productList.add(new Product("Bread", 20.00));
The products here is hard coded for example, but you may want to read it from a file or DB. More on this later.
Use generics for your Collections
Why Use Generics?
Dynamically generate your 'TextBoxes'
If you code a JPanel with 50 JTextFields for the purpose of inputting amount, what will happen when you add another product?
You will then have to go and change your code.
If you use the List of Products mentioned earlier you can dynamically generate your JTextFields
If you populated your list from a file or DB you will never have to change your code if you update your product list and/or prices. You can then just update your file or DB and the changes will reflect in your code.
List<JTextField> textFields = new ArrayList<JTextField>();
for (Product p : productList) {
textFields.add(new JTextField());
}
Then use that list along with your product list to place your Components on your JPanel
JPanel panel = new JPanel();
for (int i = 0; i < textFields.size(); i++) {
panel.add(new JLabel(productList.get(i).getName()));
panel.add(textFields.get(i));
}
Put your calculation code in a separate reusable method
private double calculateTotal(String amount, double cost) {
int amnt = Integer.parseInt(amount);
return cost * amnt;
}
Now loop through your generated 'TextBoxes' to calculate the totals
Handle the NumberFormatException that may be thrown by Integer.parseInt
private void jButton2ActionPerformed(ActionEvent evt) {
caselist = new ArrayList<String>();
for (int i = 0; i < textFields.size(); i++) {
try {
double total = calculateTotal(textFields.get(i).getText(), productList.get(i).getPrice());
caselist.add(productList.get(i).getName() +" Total - £" + total);
} catch (NumberFormatException e) {
caselist.add(productList.get(i).getName() +" invalid amount");
}
}
}
Here is everything rolled into one
so you can copy and run it to see how it all fits together.
It was put together quickly, so it is not the best way to structure your program
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ProductCalc extends JFrame {
public static void main(String[] args) {
new ProductCalc();
}
private List<Product> productList;
private List<JTextField> textFields;
private List<String> caselist;
public ProductCalc() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
productList = new ArrayList<Product>();
productList.add(new Product("Milk", 10.00));
productList.add(new Product("Bread", 20.00));
productList.add(new Product("Eggs", 5.00));
textFields = new ArrayList<JTextField>();
for (Product p : productList) {
textFields.add(new JTextField(10));
}
JPanel panel = new JPanel();
for (int i = 0; i < textFields.size(); i++) {
panel.add(new JLabel(productList.get(i).getName()));
panel.add(textFields.get(i));
}
JButton button = new JButton("click");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
panel.add(button);
this.setSize(500, 500);
this.add(panel);
this.setVisible(true);
}
private void jButton2ActionPerformed(ActionEvent evt) {
caselist = new ArrayList<String>();
for (int i = 0; i < textFields.size(); i++) {
try {
double total = calculateTotal(textFields.get(i).getText(), productList.get(i).getPrice());
caselist.add(productList.get(i).getName() + " Total - £" + total);
} catch (NumberFormatException e) {
caselist.add(productList.get(i).getName() + " invalid amount");
}
}
for (String s : caselist) {
System.out.println(s);
}
}
private double calculateTotal(String amount, double cost) {
int amnt = Integer.parseInt(amount);
return cost * amnt;
}
}
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
Some tips for you on best practices since you mentioned it:
double priceA = 20.00;
First of all double isn't exactly precise, you should watch out if you plan to use floating point variables to make any calculations that have to be 100% accurate (such as money calculations), use java.math.BigDecimal class instead.
Secondly you should store all constant (fixed) values at the top of your class where you define your variables, so you don't have any "magic numbers" roaming about.
Example: private static final double priceA = 20.00
This way you don't have to re-define the variables each time you access the method.
Thirdly you should always be suspicious of user input and handle it.
What would happen here Integer.parseInt(strA) if I for example would leave one of the text boxes empty?
Or even worse what if I would write some text there instead of numbers?
You should always be aware that users will not always use your program as intended and will even try to break it.
Finally you could define a calculating method outside of this method that would simplify your current method.
From your example it could look something like this:
private String calculcateTotal(double price, String amount) {
int actualAmount = Integer.parseInt(amount);
double totalAmount = (price * actualAmount);
return String.valueOf(totalAmount);
}
Which would reduce your original method down to:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
double priceA = 20.00;
double priceB = 25.00;
double priceC = 30.00;
ArrayList caselist = new ArrayList();
caselist.add("Case A Total - £" + calculateTotal(priceA, txtbxCaseA.getText()));
caselist.add("Case B Total - £" + calculateTotal(priceB, txtbxCaseB.getText()));
caselist.add("Case C Total - £" + calculateTotal(priceC, txtbxCaseC.getText()));
DefaultListModel myModel = new DefaultListModel ();
for(int i = 0; i < caselist.size(); i++){
jTextArea3.append((String)caselist.get(i) + ('\n'));
myModel.addElement(caselist.get(i) + ",");
/*
- save arraylist to a gobal varible for cart processing
- move to next panel (page) along
*/
}
}
See how it looks neater now?
And you could even omit the
double priceA = 20.00;
double priceB = 25.00;
double priceC = 30.00;
if you had defined them at the top of your class like I mentioned before.
My advice would be to separate the business logic from the presentation logic and you'll end up with something like this:
/**
* Represents the concept of getting a `Integer` quantity from some source.
*/
public inteface Quantity
{
public Integer getValue();
}
/**
* Represents the combination of a price and quantity to produce a total.
*/
public class Total
{
private double price;
private Quantity quantity;
public Total(double price, Quantity quantity)
{
this.price = price;
this.quantity = quantity;
}
public Double getValue()
{
Integer quantity = quantity.getValue();
return quantity != null ? quantity * price : null;
}
}
Then you can use this inteface and class in your Swing code like this (which is only intended to show the interaction with Swing, not how to layout the controls):
public class MyFrame extends JFrame
{
private static final List<Double> PRICES = Arrays.asList(20.0, 25.0, 30.0);
public MyFrame()
{
List<Total> totals = new ArrayList<Total>();
JList totalsList = new JList(new TotalListModel(totals));
addComponent(totalsList);
for (Double price : PRICES)
{
JTextField quantityTextField = new JTextField();
quantityTextField.addActionListener(new RepaintComponentActionListener(totalsList));
addComponent(quantityTextField);
totals.add(new Total(price, new TextFieldQuantity(quantityTextField)));
}
}
private class TotalListModel extends AbstractListModel
{
private List<Total> totals;
public TotalListModel(List<Total> totals)
{
this.totals = totals;
}
public Object getElementAt(int index)
{
Double value = totals.get(index).getValue();
return value != null ? value.toString() : "NO VALUE";
}
public int getSize()
{
return totals.size();
}
}
private class TextFieldQuantity implements Quantity
{
private JTextField textField;
public TextFieldQuantitySource(JTextField textField)
{
this.textField = textField;
}
public Integer getQuantity()
{
try
{
return Integer.parseInt(textField.getText());
}
catch (NumberFormatException e)
{
return null;
}
}
}
private class RepaintComponentActionListener implements ActionListener
{
private Component component;
public RefreshControlActionListener(Component component)
{
this.component = component;
}
public void actionPerformed(ActionEvent actionEvent)
{
component.repaint();
}
}
}
In case it's not immediately clear how this code is working, it uses:
a custom ListModel to wrap the totals meaning that the JList simply needs repainting and the current totals will be displayed.
a loop over the PRICES to dynamically create the JTextField controls (I'll leave it for you to work out the layout).
a custom ActionListener that repaints the JList when any of the JTextFields change.
a custom Quantity that reads the value from the JTextField.
I've reached a brick wall in a Java sample project been working on. My goal with this project is to calculate interest using user input to determine what kind of account is being used, and calculating based on each specific account type.
Right now I have created a factory method "public Account createAccount". I need it to accept the string parameter from the user prompt. To tell me if it is Checking, Savings or CD. Now here is where I run into trouble. I have to pass the user value for the "accttype" to a new object specific for each account type. My problem is I just don't know how to do this. Do I have to implement in the factory method? How can I pass these values? Thanks in advance
Account.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Account implements ActionListener {
JButton calculate;
private int period;
private int balance;
private int fbalance;
private int rate;
private int monthlyFee;
private String printstring;
#Override
public String toString() {
return String.format("Period: " + period + ", Balance: " + balance);
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public int getFbalance() {
return fbalance;
}
public void setFbalance(int fbalance) {
this.fbalance = fbalance;
}
public String getPrintstring() {
return printstring;
}
public void setPrintString(String printstring) {
this.printstring = printstring;
}
public void calculate() {
for ( int i = 0; i<period; i++)
{
fbalance = balance + balance * rate - monthlyFee;
}
}
public void actionPerformed(ActionEvent e) {
calculate();
}
}
Banker.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Banker {
// Array for type of bank account
private static void createAndShowGUI() {
// Declare strings for period, balance, rate
String period;
String balance;
String rate;
// Prompt for account type
String[] accttype = { "Checking", "Savings", "CD" }; // Array of bank acct types
String input = (String) JOptionPane.showInputDialog(null, "Choose account...",
"Choose bank account type", JOptionPane.QUESTION_MESSAGE, null,
accttype, // Array of acct types
accttype[0]); // First choice
// Prompt user for input
period = JOptionPane.showInputDialog(null, "Number of periods (length):");
balance = JOptionPane.showInputDialog(null, "Beginning balance:");
rate = JOptionPane.showInputDialog(null, "Interest rate (use decimal, example: .05 = 5%):");
// Make Calculate button
JButton calculate = new JButton("Calculate");
// Make 2 Labels
JLabel blabel = new JLabel("Period: " + period);
JLabel plabel = new JLabel("Balance: " + balance);
// Setup window with flow layout and exit on close
JFrame frame = new JFrame("Interest Savings Calculator Plus");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add combo box, calc button and labels
frame.add(calculate);
frame.add(plabel);
frame.add(blabel);
frame.pack();
frame.setVisible(true);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
public Account createAccount(String type){
}
}
If you want to use the Account class for all three account types, I suggest adding a constructor to your Account class and a variable to hold the account type like so:
public class Account implements ActionListener {
...
private String accountType = null;
public Account(String accountType) {
this.accountType = accountType;
}
...
}
Then, you can create a new Account object in the createAccount() method and return it like so:
public Account createAccount(String type) {
Account account = new Account(type);
return account;
}
Then you can simply pass the account type in (which is what your "input" variable gets set to in the createAndShowGUI() method):
Account account = createAccount(input);
Otherwise, you could also simply add the accountType variable with getters and setters, and simply create a new Account and call a set method, but I recommend using a constructor that accepts those values as parameters.
Being that you probably also want the other variables to be set in your Account object, you could call the setters on the Account object you return, or you could modify your createAccount() method and the Account constructor to accept more parameters and pass them in when you create the new Account object.