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
Related
I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}
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());
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have declared private data field without "static" modifier but when i called the data field from a method. compiler said a "static reference to the non-static method" only for one data filed "annualInterestRate" and other's seem okay.
I also declared other data with same manner but they have no problem. but in case of "annualInterestRate" data field it's give error.
import java.util.Date;
import java.util.Scanner;
public class Account {
private int id;
private double balance;
private double annualInterestRate;
private java.util.Date dateCreated;
public Account() {
}
public Account(int id, double balance, double interestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = interestRate;
dateCreated = new java.util.Date();
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getInterestRate() {
return annualInterestRate;
}
public java.util.Date getDate(){
return dateCreated;
}
public double getMonthlyInterestRate() {
double monthlyInterestRate = annualInterestRate/12.0;
return monthlyInterestRate;
}
public double getmonthlyInterest() {
double monthlyInterestRate = annualInterestRate/12.0;
return monthlyInterestRate*balance;
}
public void withdraw(double balance) {
this.balance-=balance;
}
public void deposit(double balance) {
this.balance+=balance;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int id;
double balance,interestRate,mir;
Scanner in = new Scanner(System.in);
id = in.nextInt();
balance = in.nextDouble();
interestRate = in.nextDouble();
Account Person = new Account(id, balance, interestRate);
Person.withdraw(2500.0);
Person.deposit(3000.0);
mir = getmonthlyInterest();
System.out.println(balance + " " + mir + " " + dateCreated);
}
}
expected to run smoothly
Correcting slightly your main method to use an instance of your Account class :
public static void main(String[] args) {
// TODO Auto-generated method stub
int id;
double balance,interestRate,mir;
Scanner in = new Scanner(System.in);
id = in.nextInt();
balance = in.nextDouble();
interestRate = in.nextDouble();
Account myPerson = new Account(id, balance, interestRate);
myPerson.withdraw(2500.0);
myPerson.deposit(3000.0);
mir = myPerson.getmonthlyInterest();
System.out.println(balance + " " + mir + " " + myPerson.getDate());
}
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 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.