Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
How can I compute for the balance? I want to subtract withdrawn amount to the saved entered amount of the user.
Here's my code:
AccountInformation.java
public class AccountInformation
{
private int acct_no;
private String name;
private String address;
private String bday;;
public void setAcct_No(int an)
{
this.acct_no = an;
}
public void setName(String n)
{
this.name = n;
}
public void setAddress(String ad)
{
this.address = ad;
}
public void setBday(String bd)
{
this.bday = bd;
}
public int getAcct_No()
{
return this.acct_no;
}
public String getName()
{
return this.name;
}
public String getAddress()
{
return this.address;
}
public String getBday()
{
return this.bday;
}
}
SavingsAccount.java
import javax.swing.*;
public class SavingsAccount extends AccountInformation
{
private int withdraw;
private int balance;
private int amount;
public void setAmount(int am)
{
this.amount = am;
}
public void setWithdraw(int w)
{
this.withdraw = w;
}
public void setBalance(int b)
{
this.balance = b;
}
public int getAmount()
{
return this.amount;
}
public int getWithdraw()
{
return this.withdraw;
}
public int getBalance()
{
return this.balance = amount - withdraw;
}
}
CheckingAccount.java
import javax.swing.*;
public class CheckingAccount extends AccountInformation
{
private int issue_date;
public void setIssue_Date(int id)
{
this.issue_date = id;
}
public int getIssue_Date()
{
return this.issue_date;
}
}
BankAccount.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BankAccount extends JFrame implements ActionListener
{
private JLabel acct_noL, nameL, addressL, bdayL, amountL;
private JTextField acct_noTF, nameTF, addressTF, bdayTF, amountTF;
private JButton addB, checkB, clearB, exitB;
SavingsAccount[] savings = new SavingsAccount[10];
private int index = 0;
private int acct_no = 1000;
public BankAccount()
{
for(int ctr=0;ctr<=9;ctr++)
{
savings[ctr] = new SavingsAccount();
}
setTitle("Bank Account");
setDefaultCloseOperation(EXIT_ON_CLOSE);
acct_noL = new JLabel("Account Number",SwingConstants.RIGHT);
nameL = new JLabel("Name",SwingConstants.RIGHT);
addressL = new JLabel("Address",SwingConstants.RIGHT);
bdayL = new JLabel("Birthday",SwingConstants.RIGHT);
amountL = new JLabel("Amount to Deposit",SwingConstants.RIGHT);
acct_noTF = new JTextField(10);
nameTF = new JTextField(10);
addressTF = new JTextField(10);
bdayTF = new JTextField(10);
amountTF = new JTextField(10);
acct_noTF.setText("1000");
addB = new JButton("Add");
checkB = new JButton("Check Balance");
clearB = new JButton("Clear");
exitB = new JButton("Exit");
addB.addActionListener(this);
checkB.addActionListener(this);
clearB.addActionListener(this);
exitB.addActionListener(this);
Container pane = getContentPane();
pane.setLayout(new GridLayout(7,2));
pane.add(acct_noL);
pane.add(acct_noTF);
pane.add(nameL);
pane.add(nameTF);
pane.add(addressL);
pane.add(addressTF);
pane.add(bdayL);
pane.add(bdayTF);
pane.add(amountL);
pane.add(amountTF);
pane.add(addB);
pane.add(checkB);
pane.add(clearB);
pane.add(exitB);
}
private String showAccountInfo(int an)
{
String info="";
for(int s=0;s<=9;s++)
{
if(savings[s].getAcct_No()==an)
{
info = "Account Number: " + savings[s].getAcct_No() + "\nName: " + savings[s]. getName() +
"\nAddress: " + savings[s].getAddress() + "\nBirthday " + savings[s].getBday() +
"\nBalance: " + savings[s].getAmount();
}
}
return info;
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
int inputAcct_No;
int ewithdraw;
int eissue_date;
if(source==addB)
{
if(index<=9)
{
savings[index].setAcct_No(acct_no);
savings[index].setName(nameTF.getText());
savings[index].setAddress(addressTF.getText());
savings[index].setBday(bdayTF.getText());
savings[index].setAmount(Integer.parseInt(amountTF.getText()));
index++;
acct_no++;
acct_noTF.setText(""+acct_no);
nameTF.setText(null);
addressTF.setText(null);
bdayTF.setText(null);
amountTF.setText(null);
JOptionPane.showMessageDialog(null,"Bank Account Saved!");
}
else
{
JOptionPane.showMessageDialog(null,"Bank Accounts are Full!");
}
}
if(source==checkB)
{
SavingsAccount savings = new SavingsAccount();
CheckingAccount checking = new CheckingAccount();
inputAcct_No = Integer.parseInt(JOptionPane.showInputDialog("Enter Account Number"));
JOptionPane.showMessageDialog(null,this.showAccountInfo(inputAcct_No));
int confirm_withdraw = JOptionPane.showConfirmDialog(null,"Would you like to withdraw?");
if(confirm_withdraw==JOptionPane.YES_OPTION)
{
savings.setWithdraw(Integer.parseInt(JOptionPane.showInputDialog("Enter amount to be withdrawn")));
JOptionPane.showMessageDialog(null,"Your balance is: " + (savings.getBalance()));
int confirm_issue_date = JOptionPane.showConfirmDialog(null,"Would you like to issue cheque?");
if(confirm_issue_date==JOptionPane.YES_OPTION)
{
String Receiver = JOptionPane.showInputDialog(null,"Enter name of the receiver");
checking.setIssue_Date(Integer.parseInt(JOptionPane.showInputDialog("Enter amount to be issued")));
JOptionPane.showMessageDialog(null,"Cheque is issued to " + Receiver + " with the amount of " +checking.getIssue_Date() +
"\nYour balance is: " + (savings.getBalance()-checking.getIssue_Date()));
}
}
else if(confirm_withdraw==JOptionPane.NO_OPTION)
{
}
else if(confirm_withdraw==JOptionPane.CANCEL_OPTION)
{
}
}
if(source==clearB)
{
nameTF.setText(null);
addressTF.setText(null);
bdayTF.setText(null);
amountTF.setText(null);
}
if(source==exitB)
{
System.exit(0);
}
}
public static void main(String[] args)
{
BankAccount ba = new BankAccount();
ba.setSize(500,400);
ba.setVisible(true);
ba.setResizable(false);
ba.setLocationRelativeTo(null);
}
}
"I want to subtract withdrawn amount to the saved entered amount of the user."
Here's is your withdraw code
public void setWithdraw(int w)
{
this.withdraw = w;
}
There is no need to even have a withdraw field to set, unless you want a list of transactions or something, which you don't have. So take out the withdraw field from the class. It doesn't need to be set. And just do something like this
public void withdraw(int amount)
{
balance -= amount;
}
All you need to do is subtract the amount from the balance. Do the same with your deposits (If you decide to add a deposit method. After all, what's an account if you can't deposit).
EDIT
Also you're creating a new Account every time actionPerformed is called
SavingsAccount Savings = new SavingsAccount();
CheckingAccount checking = new CheckingAccount();
Don'r do that. That's why the widthraw amount is always the same as the balance. Instead put them as class member. And remove the above code from the actionPerformed
UPDATE
Try running this very simple program. You will see how withdrawing should work
import java.util.Scanner;
public class AccountTest {
public static void main(String[] args) {
Account account = new Account(1000.00);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a Amount to withdraw: ");
double amountToWithdraw = scanner.nextDouble();
account.withDraw(amountToWithdraw);
System.out.println("You balance is now " + account.getBalance());
}
}
class Account{
double balance;
public Account(double initialBalance) {
balance = initialBalance;
}
public double getBalance(){
return balance;
}
public void withDraw(double amount) {
balance -= amount;
}
}
EDIT
Here's a suggestion. I see you have a SavingsAccount array. So you probably want multiple accounts. I also you that you're trying to access a specific account by account id in the actionPerformed if the checkB is pressed. What you should do then, if loop through the array and if the id is found, then use that account to do your work. Something like this
inputAcct_No = Integer.parseInt(JOptionPane.showInputDialog("Enter Account Number"));
SavingsAccount savings;
for (SavingsAccount account : SavingsAccounts){ <-- your array
if (acound.getId() == inputAcct_No){
savings = account;
}
}
// do something with savings
Now you can do something with that account because it is referencing the account in the array.
Its better to tell the exact issue you are facing , its difficult to check the complete code..
At a galance what i got is that in your SavingsAccount class getBalance() method you are simply subtracting and returning but there is no effect on the actual value of balance.
What i think you have to do balance-withdraw in your setWithdraw() method.
Related
I'm trying to use a setter/getter class in multiple classes to modify a single variable. I understand that I have to use the same object in order for this to work, but I'm unsure on how to make a single object accessible to multiple classes.
public class accountbalance {
private double balance;
//getter
public double getBalance() {
return balance;
}
//Setter
public void setBalance(double newBalance) {
this.balance = newBalance;
}
}
This is where I'm trying to use it first:
public class CreateAccount {
String name;
double social;
int pin;
public CreateAccount()
{
name = "null";
social = 0;
pin = 0;
}
public CreateAccount(String enteredName, double enteredSocial,int enteredPin, double value)
{
name = enteredName;
social = enteredSocial;
pin = enteredPin;
double accountnum = 87495;
accountbalance a1 = new accountbalance();
a1.setBalance(value);
System.out.println(name);
System.out.println(social);
System.out.println("Your new PIN is " + pin);
System.out.println("Your new account balance is " + (a1.getBalance()));
}
}
And then I'm trying to use it again here:
public class deposit {
double enteredAmt;
double amt;
public void deposit() {
System.out.println("Enter an amount to desposit: ");
Scanner in = new Scanner(System.in);
enteredAmt = in.nextDouble();
accountbalance ab1 = new accountbalance();
System.out.println("current balence: " + ab1.getBalance());
amt = ab1.getBalance() + enteredAmt;
ab1.setBalance(amt);
System.out.println("Your new balance is " + (ab1.getBalance()));
}
}
I believe what you're trying to do is use the Command Design Pattern.
If you changed your classes to look more like this, things might work a tad bit better.
public class Account {
// Please do not use SS for an identifier.
private String identifier;
private String name;
// Money needs to be stored in it's lowest common denominator.
// Which in the united states, is pennies.
private long balance;
public Account(String identifier, String name) {
this.identifier = identifier;
this.name = name;
this.balance = 0L;
}
public String getIdentifier() {
return this.identifier;
}
public String getName() {
return this.name;
}
public long getBalance() {
return balance;
}
public void credit(long amount) {
balance =+ amount;
}
public void debit(long amount) {
balance =- amount;
}
}
Then here would be your CreateAccountCommand. It is a bit anemic, but that is ok.
public class CreateAccountCommand {
private String identifier;
private String name;
public CreateAccount(String identifier, String name) {
// Identifier sould actually be generated by something else.
this.identifier = identifier;
name = name;
}
public Account execute() {
return new Account(identifier, name);
}
}
Here is your DepositCommand:
public class DepositCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.credit(amount);
}
}
WithdrawCommand:
public class WithdrawCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.debit(amount);
}
}
Then run everything:
public class Run {
public static void main(String... args) {
CreateAccountCommand createAccountCommand = new CreateAccountCommand("12345678", "First_Name Last_Name");
Account account = createAccountCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Deposit $100.00
DepositCommand depositCommand = new DepositCommand(account, 10000);
depositCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Withdraw $75.00
WithdrawCommand withdrawCommand = new WithdrawCommand(account, 7500);
withdrawCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
}
}
I'm trying to ask the user for an input in the "doDeposit" method and check if the ID entered matches one from the file, however I get the error "at java.util.Scanner.throwFor(Unknown Source)" when trying to use the Scanner.
The file it my program reads from has the following data:
Brain Adams,51,B10000,3000.5,1
John Waterson,30,B10001,4000.34,0
John Key,61,B10002,56666600,2
Julia Roberts,28,B10003,454545,1,
Tom Cruise,27,B10004,340000000,1
Johnny Tom,54,B10005,230,0
Joe Haldeman,66,B10006,23055.5,0
Charles King,55,B10007,2400.5,0
James Thomson,44,B10008,330.5,0
Cameron Diaz,28,B10009,23000000.6,1
Barak Obama,84,B10010,2000000.4,2
Dustin Hoffman,37,B10011,23000000,1
Robin Williams,72,B10012,22000000.5,1
Russell Crowe,47,B10013,44000000.3,1
Kylie Minogue,28,B10014,10000000.3,1
Paul Keating,41,B10015,4000000.8,2
Lady Gaga,32,B10016,50000000,1
Helen Clark,502,B10017,400000,2
Mikhail Suzenski,32,B10018,0.0,0
Boris Yeltsin,21,B10019,10000000.5,2
My code:
package assignment;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import static java.lang.System.out;
public class Assignment
{
public static void main(String[] args)
{
try
{
new
BankAccountApp("C:/Users/USER/workspace/assignment/data/AssignmentData");
}
catch (IOException ioe)
{
out.printf("Missing file: %sC:/Users/USER/workspace/assignment/data/AssignmentData? \n\n",
new Assignment().getClass().getPackage().getName());
}
}
}
class BankAccountApp
{
private List<BankAccount> accounts;
public BankAccountApp(String filename) throws IOException
{
readAccountData(filename);
displayMenu();
int opt = 0;
try (Scanner input = new Scanner(System.in))
{
while (true)
{
out.print("\nSelect an option: ");
opt = input.nextInt();// format exception if string
if (opt < 0 || opt > 7)
out.println("Invalid. Must be 1 - 7 (or 0 for menu).");
else
break;
}
}
switch (opt)
{
case 0: displayMenu(); break;
case 1: doDeposit(); break;
case 2: doWithdraw(); break;
case 3: displayHighestBalanceAccount(); break;
case 4: displayMostActiveAccount(); break;
case 5: displayAllAccounts("C:/Users/USER/workspace/assignment/data/AssignmentData"); break;
case 6:
{
int total = getTotalTransactions(accounts);
out.println("Total transactions: " + total);
break;
}
case 7: farewell(); return;
}
}
public void readAccountData(String fn) throws IOException
{
accounts = new LinkedList<>();
Path path = new File("C:/Users/USER/workspace/assignment/data/AssignmentData").toPath();
List<String> content = Files.readAllLines(path);
for(String line : content){
String[] items = line.split(",");
String name = items[0];
int age = Integer.valueOf(items[1]);
String accountID = items[2];
double balance = Double.valueOf(items[3]);
int accountType = Integer.valueOf(items[4]);
BankAccount b = new BankAccount(name, age, accountID, balance, accountType);
accounts.add(b);
}
}
public void displayAllAccounts(String fn) throws IOException
{
accounts = new LinkedList<BankAccount>();
Path path = new File(fn).toPath();
List<String> content = Files.readAllLines(path);
for(String line : content){
String[] items = line.split(",");
String name = items[0];
int age = Integer.valueOf(items[1]);
String accountID = items[2];
double balance = Double.valueOf(items[3]);
int accountType = Integer.valueOf(items[4]);
BankAccount b = new BankAccount(name, age, accountID, balance, accountType);
accounts.add(b);
out.printf("---All Bank Accounts---\n");
out.println("Name: "+name);
out.println("Age: "+age);
out.println("Account ID: "+accountID);
out.printf("Account Balance: %f",balance);
out.println("\nAccount Type: "+accountType+"\n");
}
return;
}
public void displayHighestBalanceAccount()
{
BankAccount mostMoney = accounts.get(3);
for(BankAccount b : accounts){
if(mostMoney.getbalance() < b.getbalance()){
mostMoney = b;
}
}
String name = mostMoney.getname();
int age = mostMoney.getage();
String accountID = mostMoney.getaccountID();
double balance = mostMoney.getbalance();
int accountType = mostMoney.accountType();
out.printf("---Bank account with the highest balance---\n");
out.println("Name: "+name);
out.println("Age: "+age);
out.println("Account ID: "+accountID);
out.printf("Account Balance: %f",balance);
out.println("\nAccount Type: "+accountType);
}
public void displayMostActiveAccount()
{
}
public int getTotalTransactions(List<BankAccount> list)
{
return 0;
}
public void doDeposit()
{
out.print("Enter an account ID for deposit: ");
}
public void doWithdraw()
{
}
public void farewell()
{
out.println("Thanks for using the service. Bye!");
}
public void displayMenu()
{
out.println("*********************************");
out.println("* Bank Account Operation Menu *");
out.println("***********************************\n");
out.println("0. Display Menu");
out.println("1. Deposit");
out.println("2. Withdraw");
out.println("3. Display Highest Balance Account");
out.println("4. Display Most Active Account");
out.println("5. Display All Accounts");
out.println("6. Display Total Number of Transactions");
out.println("7. Exit");
}
}
class BankAccount1 extends Person1
{
private String accountID;
private double balance;
private int accountType;
public String getaccountID() {
return accountID;
}
public void setaccountID(String accountID) {
this.accountID = accountID;
}
public double getbalance() {
return balance;
}
public void setbalance(double balance) {
this.balance = balance;
}
public int accountType() {
return accountType;
}
public void setaccountType(int accountType) {
this.accountType = accountType;
}
public BankAccount1(String name, int age, String accountID, double balance, int accountType)
{
super(name, age);
this.accountID = accountID;
this.balance = balance;
this.accountType = accountType;
}
}
class Person1 {
private String name;
private int age;
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age = age;
}
public Person1(String name, int age)
{
this.name = name;
this.age = age;
}
}
Any pointers are much appreciated.
I ran your code. I found two errors.
you have a BankAccount1 class and You refers to BankAccount. without "1".
You use a wrong path
See your path is
C:/Users/USER/workspace/assignment/data/AssignmentData
But Path should be like below
C:\\Users\\Menuka\\IdeaProjects\\JavaTest\\src\\AssignmentData`
I'll post full code below.
https://gist.github.com/Menuka5/2af4d16dccbdf780d730fd8bf5ce4e56
it is showing me "cannot find symbol method printIn(java.lang.string)
please what is the error, i have used 3 different IDES.
whats wrong with the System.out.printIn()
public class Account
{
private String owner;
private int balance;
public Account (String name)
{
owner = name;
balance = 0;
}
public void deposit(int anAmount)
{
balance += anAmount;
}
public int withdraw(int anAmount)
{
int amountWithdrawn;
if (anAmount <= balance )
amountWithdrawn = anAmount;
else
amountWithdrawn = balance;
balance -= amountWithdrawn;
return amountWithdrawn;
}
public void print()
{
System.out.printIn("Owner =" + owner +" Balance=" + balance);
}
}
That is not printIn(). You typed letter I for Ikea
That is println() you had to use letter l for lima
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please I would like know How would I implement JOptionPane instead of import java.util.Scanner;
I also have 4 separate classes
If i implement JOptionPane will it clean up the code I would also like to know any changes anyone would make.
Employee.Class
import java.text.NumberFormat;
import java.util.Scanner;
public class Employee {
public static int numEmployees = 0;
protected String firstName;
protected String lastName;
protected char gender;
protected int dependents;
protected double annualSalary;
private NumberFormat nf = NumberFormat.getCurrencyInstance();
public Benefit benefit;
private static Scanner scan;
public Employee() {
firstName = "";
lastName = "";
gender = 'U';
dependents = 0;
annualSalary = 40000;
benefit = new Benefit();
numEmployees++;
}
public Employee(String first, String last, char gen, int dep, Benefit benefit1) {
this.firstName = first;
this.lastName = last;
this.gender = gen;
this.annualSalary = 40000;
this.dependents = dep;
this.benefit = benefit1;
numEmployees++;
}
public double calculatePay1() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("First Name: ").append(firstName).append("\n");
sb.append("Last Name: ").append(lastName).append("\n");
sb.append("Gender: ").append(gender).append("\n");
sb.append("Dependents: ").append(dependents).append("\n");
sb.append("Annual Salary: ").append(nf.format(getAnnualSalary())).append("\n");
sb.append("Weekly Pay: ").append(nf.format(calculatePay1())).append("\n");
sb.append(benefit.toString());
return sb.toString();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public <Gender> void setGender(char gender) {
this.gender = gender;
}
public <Gender> char getGender() {
return gender;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}
public void setDependents(String dependents) {
this.dependents = Integer.parseInt(dependents);
}
public int getDependents() {
return dependents;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualSalary(String annualSalary) {
this.annualSalary = Double.parseDouble(annualSalary);
}
public double getAnnualSalary() {
return annualSalary;
}
public double calculatePay() {
return annualSalary / 52;
}
public double getAnnualSalary1() {
return annualSalary;
}
public static void displayDivider(String outputTitle) {
System.out.println(">>>>>>>>>>>>>>> " + outputTitle + " <<<<<<<<<<<<<<<");
}
public static String getInput(String inputType) {
System.out.println("Enter the " + inputType + ": ");
scan = new Scanner(System.in);
String input = scan.next();
return input;
}
public static int getNumEmployees() {
return numEmployees;
}
public static void main(String[] args) {
displayDivider("New Employee Information");
Benefit benefit = new Benefit();
Employee employee = new Employee("George", "Anderson", 'M', 5, benefit);
System.out.println(employee.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Temp Employee Information");
Hourly hourly = new Hourly("Mary", "Nola", 'F', 5, 14, 45, "temp");
System.out.println(hourly.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Full Time Employee Information");
Hourly hourly1 = new Hourly("Mary", "Nola", 'F', 5, 18, 42, "full time");
System.out.println(hourly1.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Hourly Part Time Employee Information");
Hourly hourly11 = new Hourly("Mary", "Nola", 'F', 5, 18, 20, "part time");
System.out.println(hourly11.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Revised Employee Information");
Benefit benefit1 = new Benefit("None", 500, 3);
Salaried salaried = new Salaried("Frank", "Lucus", 'M', 5, 150000, benefit1, 3);
System.out.println(salaried.toString());
System.out.println("Total employees: " + getNumEmployees());
displayDivider("Salaried Employee Information");
Benefit benefit11 = new Benefit("None", 500, 3);
Salaried salaried1 = new Salaried("Frank", "Lucus", 'M', 5, 100000, benefit11, 2);
System.out.println(salaried1.toString());
System.out.println("Total employees: " + getNumEmployees());
}
}
SALARIED.CLASS
import java.util.Random;
import java.util.Scanner;
public class Salaried extends Employee {
private static final int MIN_MANAGEMENT_LEVEL = 0;
private static final int MAX_MANAGEMENT_LEVEL = 3;
private static final int BONUS_PERCENT = 10;
private int managementLevel;
private Scanner in;
public Salaried() {
super();
Random rand = new Random();
managementLevel = rand.nextInt(4) + 1;
if (managementLevel == 0) {
System.out.println("Not Valid");
}
//numEmployees++;
}
private boolean validManagementLevel(int level) {
return (MIN_MANAGEMENT_LEVEL <= level && level <= MAX_MANAGEMENT_LEVEL);
}
public Salaried(String fname, String lname, char gen, int dep,
double sal, Benefit ben, int manLevel)
{
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = sal;
super.benefit = ben;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter
another management level value in range [0,3]: ");
manLevel = new Scanner(System.in).nextInt();
} else {
managementLevel = manLevel;
break;
}
}
//numEmployees++;
}
public Salaried(double sal, int manLevel) {
super.annualSalary = sal;
while (true) {
if (!validManagementLevel(manLevel)) {
System.out.print("Invalid management level, please enter another
management level value in range [0,3]: ");
in = new Scanner(System.in);
manLevel = in.nextInt();
} else {
managementLevel = manLevel;
break;
}
}
// numEmployees++;
}
#Override
public double calculatePay() {
double percentage = managementLevel * BONUS_PERCENT;
return (1 + percentage/100.0) * annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Management Level: ").append(managementLevel).append("\n");
return sb.toString();
}
}
Hourly.Class
import java.util.Scanner;
public class Hourly extends Employee {
private static final double MIN_WAGE = 10;
private static final double MAX_WAGE = 75;
private static final double MIN_HOURS = 0;
private static final double MAX_HOURS = 50;
private double wage;
private double hours;
private String category;
private Scanner in;
private Scanner in2;
private Scanner in3;
private Scanner in4;
public Hourly() {
super();
this.wage = 20;
this.hours= 30;
this.category = "full time";
annualSalary = wage * hours * 52;
}
public Hourly(double wage_, double hours_, String category_) {
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage: ");
in2 = new Scanner(System.in);
wage_ = in2.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours: ");
in = new Scanner(System.in);
hours_ = in.nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
category_ = new Scanner(System.in).next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
public Hourly(String fname, String lname, char gen, int dep, double wage_,double hours_, String category_) {
super.firstName = fname;
super.lastName = lname;
super.gender = gen;
super.dependents = dep;
super.annualSalary = annualSalary;
super.benefit = benefit;
while (true) {
if (!validWage(wage_)) {
System.out.print("Invalid wage : ");
in3 = new Scanner(System.in);
wage_ = in3.nextDouble();
} else {
this.wage = wage_;
break;
}
}
while (true) {
if (!validHour(hours_)) {
System.out.print("Invalid hours : ");
hours_ = new Scanner(System.in).nextDouble();
} else {
this.hours = hours_;
break;
}
}
while (true) {
if (!validCategory(category_)) {
System.out.print("Invalid category, please enter another category value: ");
in4 = new Scanner(System.in);
category_ = in4.next();
} else {
this.category = category_;
break;
}
}
annualSalary = wage * hours * 52;
//numEmployees++;
}
private boolean validHour(double hour) {
return (MIN_HOURS <= hour && hour <= MAX_HOURS);
}
private boolean validWage(double wage) {
return (MIN_WAGE <= wage && wage <= MAX_WAGE);
}
private boolean validCategory(String category) {
String[] categories = {"temp", "part time", "full time"};
for (int i = 0; i < categories.length; i++)
if (category.equalsIgnoreCase(categories[i]))
return true;
return false;
}
public double calculatePay() {
return annualSalary / 52;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append("Wage: ").append(wage).append("\n");
sb.append("Hours: ").append(hours).append("\n");
sb.append("Category: ").append(category).append("\n");
return sb.toString();
}
}
Benefit.Class
public class Benefit {
private String healthInsurance;
private double lifeInsurance;
private int vacationDays;
public Benefit() {
healthInsurance = "Full";
lifeInsurance = 100;
vacationDays = 5;
}
public Benefit(String health, double life, int vacation) {
setHealthInsurance(health);
setLifeInsurance(life);
setVacation(vacation);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Health Insurance: ").append(healthInsurance).append("\n");
sb.append("Life Insurance: ").append(lifeInsurance).append("\n");
sb.append("Vacation Days: ").append(vacationDays).append("\n");
return sb.toString();
}
public void setHealthInsurance(String healthInsurance) {
this.healthInsurance = healthInsurance;
}
public String getHealthInsurance() {
return healthInsurance;
}
public void setLifeInsurance(double lifeInsurance) {
this.lifeInsurance = lifeInsurance;
}
public double getLifeInsurance() {
return lifeInsurance;
}
public void setVacation(int vacation) {
this.vacationDays = vacation;
}
public int getVacation() {
return vacationDays;
}
public void displayBenefit() {
this.toString();
}
}
Start by taking a look at How to Make Dialogs...
What you basically want is to use JOptionPane.showInputDialog, which can be used to prompt the use for input...
Yes, there are a few flavours, but lets keep it simply and look at JOptionPane.showInputDialog(Object)
The JavaDocs tells us that...
message - the Object to display
Returns:user's input, or null meaning the user canceled the input
So, from that we could use something like...
String value = JOptionPane.showInputDialog("What is your name?");
if (value != null) {
System.out.println("Hello " + value);
} else {
System.out.println("Hello no name");
}
Which displays...
Now, if we take a look at your code, you could replace the use of scan with...
public static String getInput(String inputType) {
String input = JOptionPane.showInputDialog("Enter the " + inputType + ": ");
return input;
}
As an example...
Now, what I might recommend is creating a simple helper method which can be used to prompt the user in a single line of code, for example...
public class InputHelper {
public static String promptUser(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
which might be used something like...
String value = InputHelper.promptUser("Please enter the hours worked");
hours_ = Double.parse(value);
And this is where it get's messy, as you will now need to valid the input of the user.
You could extend the idea of the InputHelper to do automatic conversions and re-prompt the user if the value was invalid...as an idea
It is much easier than you think, if you try. Get used to reading the Java API.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Even has examples.
String input;
JOptionPane jop=new JOptionPane();
input=jop.showInputDialog("Question i want to ask");
System.out.println(input);
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
So I have an assignment in Advanced Inheritance for Java and have the code pretty much hammered out but am having issues finishing it off and making it actually display the output. The program was split into 4 different parts and I have them listed below.
Account.java
public abstract class Account
{
protected long accountNumber;
protected double accountBalance;
public long getAccountNumber()
{
return accountNumber;
}
public double getAccountBalance()
{
return accountBalance;
}
public void setAccountNumber(long number)
{
number = accountNumber;
}
public void setAccountBalance(double balance)
{
balance = accountBalance;
}
public void setUpAccount(long number, double balance) //look up constructors
{
number = accountNumber;
balance = accountBalance;
}
public String toString()
{
return "Account Number: " + accountNumber + " Account Balance: " + accountBalance;
}
public abstract double computeInterest(int intPeriod);
}
Checkings.java
public class Checking extends Account
{
public String toString()
{
String info = "Checking\nAccount Number: " + accountNumber +
"\nAccount Balance: " + accountBalance ;
return info;
}
public Checking(long number)
{
number = accountNumber;
}
public double computeInterest(int intPeriod)
{
double total = ((accountBalance - 700) * .02) * 3;
return total;
}
}
Savings.java
public class Savings extends Account
{
private double interestRate;
public double getInterest()
{
return interestRate;
}
public void setInterest(double inter)
{
inter = interestRate;
}
public String toString()
{
String info = "Savings\nAccount Number: " + accountNumber + " \nAccount Balance: "
+ accountBalance + " \nInterest Rate: " + interestRate;
return info;
}
public Savings(long number, double interest)
{
number = accountNumber;
interest = interestRate;
}
public double computeInterest(int intPeriod)
{
double total = Math.pow((1 + interestRate), intPeriod) * accountBalance - accountBalance;
return total;
}
}
AccountArray.java
public class AccountArray
{
public static void main(String[] args)
{
Account[] refAccount = new Account[10];
/*refAccount[0] = new Checking(100);
refAccount[1] = new Checking(101);
refAccount[2] = new Checking(102);
refAccount[3] = new Checking(103);
refAccount[4] = new Checking(104);
refAccount[5] = new Savings(105, .02);
refAccount[6] = new Savings(106, .02);
refAccount[7] = new Savings(107, .02);
refAccount[8] = new Savings(108, .02);
refAccount[9] = new Savings(109, .02);
refAccount[0].setAccountBalance(1000.0);
refAccount[1].setAccountBalance(2000.0);
refAccount[2].setAccountBalance(3000.0);
refAccount[3].setAccountBalance(4000.0);
refAccount[4].setAccountBalance(5000.0);
refAccount[5].setAccountBalance(6000.0);
refAccount[6].setAccountBalance(7000.0);
refAccount[7].setAccountBalance(8000.0);
refAccount[8].setAccountBalance(9000.0);
refAccount[9].setAccountBalance(10000.0);*/
for(int inc = 0; inc < 10; inc++ )
{
refAccount[0] = new Checking(100);
refAccount[1] = new Checking(101);
refAccount[2] = new Checking(102);
refAccount[3] = new Checking(103);
refAccount[4] = new Checking(104);
refAccount[5] = new Savings(105, .02);
refAccount[6] = new Savings(106, .02);
refAccount[7] = new Savings(107, .02);
refAccount[8] = new Savings(108, .02);
refAccount[9] = new Savings(109, .02);
refAccount[0].setAccountBalance(1000.0);
refAccount[1].setAccountBalance(2000.0);
refAccount[2].setAccountBalance(3000.0);
refAccount[3].setAccountBalance(4000.0);
refAccount[4].setAccountBalance(5000.0);
refAccount[5].setAccountBalance(6000.0);
refAccount[6].setAccountBalance(7000.0);
refAccount[7].setAccountBalance(8000.0);
refAccount[8].setAccountBalance(9000.0);
refAccount[9].setAccountBalance(10000.0);
}
for(int ctr = 0; ctr < 10; ctr++)
{
System.out.println(refAccount[ctr].toString());
}
}
}
Is there something I'm like really obviously missing? It all compiles just fine but the output just displays 0s instead of the Account Numbers, Balance or Interest.
Any help would be very much appreciated since I'm running out of time.
All of your setter methods look the wrong way round, you've got them as...
public void setAccountNumber(long number)
{
number = accountNumber;
}
public void setAccountBalance(double balance)
{
balance = accountBalance;
}
All you're doing there is setting the parameter value, they should be...
public void setAccountNumber(long number)
{
accountNumber= number;
}
public void setAccountBalance(double balance)
{
accountBalance= balance;
}
You can make sure this doesn't happen my making your parameters final
Have a look at your constructors and setters You inverse your variable attribution
Ex
public void setAccountNumber(long number)
{
number = accountNumber;
}
should be
public void setAccountNumber(long number)
{
accountNumber = number;
}
same for all your setters and constructors