I'm trying to make it so each transaction is time stamped, but I'm having an issue with the date object. I keep running into a syntax error every time the program gets to the constructor. Any ideas?
Thank you so much!!!
UPDATE: I changed it so the constructor class now says:
DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm");
Date dateobj = new Date();
But now I run into a null pointer expression as soon as it's called in the MainMenu method. How do I get it to work in all the methods like the array list?
/**
* Bank Account
*
* #author: Seth Killian
* #version: 1.
* #citations: All okay. Adapted online tutorials in using the scanner tools to create a menu and list array.
*/
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
//import java.util.Calendar;
public class BankAccount
{
private double minbalance; // Minimum allowable account balance
private double maxdeposit; // Maximum allowable deposit
private double balance; // Account balance
private double rate; // Rate of annual interest in value of percent
private String AcctName; // Account name
private ArrayList<String> transactions;
public Date dateobj;
public DateFormat df;
/**
* Constructor for Bank Account Class with Starting Balance
* #param: Starting Balance
* #return: None
*/
public BankAccount(double startBalance)
{
DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm");
Date dateobj = new Date();
transactions = new ArrayList<String>();
balance = startBalance;
transactions.add("+ $" + startBalance + " Initial Balance " + df.format(dateobj) + " Bal: $" + balance);
minbalance = 0.25;
maxdeposit = 5000.00;
rate = 6; // Six percent annual interest
AcctName = "Seth Killian";
}
/**
* Main Menu which allows the user to select from options
* #param: None
* #return: None
*/
public void MainMenu()
{
Scanner in = new Scanner (System.in);
switch (in.nextInt())
{
case 0:
Initialize();
case 1:
System.out.println("Balance: $" + balance + " as of " + df.format(dateobj));
SelectOption();
case 2: //Make a deposit
double amount;
System.out.print("Deposit Amount: $");
amount = in.nextDouble();
if (!(amount > 0) || (amount > maxdeposit))
{transactions.add("* Attempted Deposit: $" + amount + " " + df.format(dateobj));}
if (!(amount > 0))
{System.out.println("Error: Amount must be greater than zero");}
else if (amount > maxdeposit)
{System.out.println("Error: Maximum Deposit $" + maxdeposit + ".");}
else
{
balance += amount;
transactions.add("+ $" + amount + " Deposit " + df.format(dateobj) + " Bal: $" + balance);
System.out.println("Success: Deposited $" + amount + " Balance: $" + balance);
}
SelectOption();
case 3: //Make a withdrawl
System.out.print("Withdrawl Amount: $");
amount = in.nextDouble();
if (!(amount > 0) || (amount > balance) || (balance-amount < minbalance))
{transactions.add("* Attempted Withdrawl: $" + amount + " " + df.format(dateobj));}
if (!(amount > 0))
{System.out.println("Error: Amount must be greater than zero");}
else if (amount > balance)
{System.out.println("Error: Insufficent Funds");}
else if (balance-amount < minbalance)
{System.out.println("Error: Minimum Balance $" + minbalance + ".");}
else
{
balance -= amount;
transactions.add("- $" + amount + " Withdrawl " + df.format(dateobj) + " Bal: $" + balance);
System.out.println("Success: Withdrew $" + amount + " Balance: $" + balance);
}
SelectOption();
case 4: //Apply Annual Interest
balance = balance + (balance * (rate/100.0));
transactions.add("Interest ("+ rate + "%) "+ df.format(dateobj) + " Bal: $" + balance);
System.out.println("Success: " + rate + "% Interest rate applied. Balance: $" + balance);
SelectOption();
case 5: // Print Log
System.out.println();
System.out.println("Transaction Log for " + AcctName);
System.out.println("---------------------------------------- ");
for(int x = 0; x < transactions.size(); x++)
{System.out.println(transactions.get(x));}
System.out.println("---------------------------------------- ");
SelectOption();
case 6: // Exits application
System.exit(0);
default: // Unrecognized Selection
System.out.println ("Error: Selection Unrecognized");
SelectOption();
}
}
/**
* Sets the Main Menu up
* #param: None
* #return: None
*/
public void Initialize()
{
System.out.print('\u000C'); // Clears the terminal screen
System.out.println("Welcome " + AcctName + "!");
System.out.println("======================================== ");
System.out.println("1) Check Balance\n2) Make a Deposit\n3) Make a Withdrawl\n4) Add Annual Interest\n5) Transaction Logs");
System.out.println("\n0) Clear Screen\n6) Exit Application");
System.out.println("======================================== ");
SelectOption();
}
/**
* Allows the user to make a selection.
* #param: None
* #return: None
*/
public void SelectOption()
{
System.out.print ("Selection: ");
MainMenu();
}
}
From Class SimpleDateFormat
Any characters in the pattern that are not in the ranges of ['a'..'z'] and ['A'..'Z'] will be treated as quoted text. For instance, characters like ':', '.', ' ', '#' and '#' will appear in the resulting time text even they are not embraced within single quotes.
A pattern containing any invalid pattern letter will result in a thrown exception during formatting or parsing.
Thus your line of code df = new SimpleDateFormat("MM/dd/yy HH:mm"); will throw an exception because of the /. Try putting the / in single quotes.
df = new SimpleDateFormat("MM'/'dd'/'yy HH:mm");
Also like #DavidColer's answer states, you never initialize your Date object.
Update
After testing it turns out that df = new SimpleDateFormat("MM/dd/yy HH:mm"); will work without the single quotes. I should have taken a look at Oracle's documentation here.
You need to either create an instance of your BankAccount class by passing a double, like so BankAccount ba = new BankAccount(100.0); or add a default constructor in your class. Like the following.
public BankAccount() {
this(0.25);
}
You never fully initialize the date.
DateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm");
Date date = new Date();
System.out.println(simpleDateFormat.format(date));
I do not see anywhere where you use your overloaded constructor or even instantiate an instance of your bankaccount class where is it in the code? if you are not using the overloaded constructor you should create a default constructor to instantiate your varibales.
public class BankAccount
{
final private double MINBALANCE; // Minimum allowable account balance
final private double MAXDEPOSIT; // Maximum allowable deposit
private double balance; // Account balance
private double rate; // Rate of annual interest in value of percent
private String AcctName; // Account name
private ArrayList<String> transactions;
public Date dateobj;
public DateFormat df;
public BankAccount()
{
MINBALANCE = 25.00; // Minimum allowable account balance this should be all caps for a constant
MAXDEPOSIT = 5000.00; // Maximum allowable deposit should also be a constant
balance = 0.0;
rate = 0.0;
AcctName = null;
transactions = new ArrayList<String>(10);
dateobj = new Date();
df = new SimpleDateFormat("MM/dd/yy HH:mm");
}
;
like so
Related
okay so to the preface the situation. I have been given an assignment with various tasks. So far I have created a Canteen Account(which will be shown below), a main menu class, and now I have to make another class which inherits from Canteen Account, called StaffAccount. A StaffAccount object should contain the following additional property :
discountRate - the rate (percentage) discount applied to all purchases
A StaffAccount object should contain the following additional methods:
(i) StaffAccount (String newId, String newName, double discountRate)
A constructor method to initialise the StaffAccount object’s properties via the three parameters.
In the staff account I am having issues with a method called PayForMeal(which is an overridden method) which in the assignment brief has the purpose of:
A method to record the cost of a meal. The balance on a StaffAccount object should be amended to reflect discount on the cost of a meal (if the cost does not exceed available balance).
If the cost exceeds the balance then an Exception will be thrown to warn the customer they must topUp their balance – if the customer is within their credit limit a negative value will be recorded in the balance and the status of the account changed to show that the customer is using credit.
No discount should be applied if the customer is using credit.
So my issue is, how do I make a staff account using the constructor given to me, and then use the payForMeal overridden method to apply a discount to the amount a meal costs, then take the discounted amount away from a balance which is not there because it is not in the constructor for the StaffAccount, but it is in the constructor for the CanteenAccount. The classes are below, i just want to know if this is possible or am I being dumb
//////CANTEEN ACCOUNT \\\\\\\\
public class CanteenAcc
{
private String customerId;
private String name;
private double balance;
private static double minTopup = 2.00;
private String status;
private static double creditLimit = 5.00;
private static int transCount;
/**
* Constructor to create a Canteen account object using three parameters
* #param newId - String
* #param newName - String
* #param newBalance - Double
*/
public CanteenAcc(String newId, String newName, double newBalance)
{
this.customerId = newId;
this.name = newName;
this.balance = newBalance;
}
public CanteenAcc(String newId, String newName)
{
this.customerId = newId;
this.name = newName;
}
//BEFORE EVERY METHOD AND CLASS YOU SHOULD HAVE JAVADOC COMMENTS.
public void topUp(double depositAmount)
{
if(depositAmount > 0)
{
this.balance += depositAmount;
this.status = "Valid";
}else
{
this.status = "Invalid";
}
}
public void payForMeal(double amount) throws Exception
{
if(balance - amount < 0 && amount - balance <= creditLimit)
{
this.status = "Using Credit";
double newBalance = balance - amount;
balance = newBalance;
throw new Exception("\n\n-----------------------------\n"
+ "You must top-up your balance\n"
+ "Your new balance is: "+ balance + " GBP" +"\n"
+ "You are: " + status + "\n"
+ "-----------------------------\n");
}
else if(amount > creditLimit && balance < amount)
{
throw new Exception("\n\n------------------------------\n"
+ "Cost exceeds the credit limit."
+ "\n------------------------------\n");
}
else
{
double newBalance = balance - amount;
balance = newBalance;
transCount++;
}
}
public String displayAccountDetails()
{
StringBuilder ad = new StringBuilder();
ad.append("------------------------\n");
ad.append("****Account Details****\n");
ad.append("------------------------\n");
ad.append("\n");
ad.append("****Customer ID****: \n" + customerId + "\n");
ad.append("\n");
ad.append("****Name****: \n" + name + "\n");
ad.append("------------------------\n");
ad.append("\n");
return ad.toString();
}
public String getStatistics()
{
StringBuilder as = new StringBuilder();
as.append("------------------------\n");
as.append(" CANTEEN ACCOUNT \n");
as.append("------------------------\n");
as.append("\n");
as.append("****Transaction Count****\n");
as.append(transCount + "\n");
as.append("\n");
as.append("****Account Balance****\n");
as.append(balance + "\n");
as.append("\n");
as.append("***Account Status****\n");
as.append(status + "\n");
as.append("------------------------\n");
return as.toString();
}
public double getBalance()
{
return balance;
}
public double getCreditLimt()
{
return creditLimit;
}
public double getMinTopup()
{
return minTopup;
}
public String getStatus()
{
return status;
}
public static void updateCreditLimit(double newLimit)
{
creditLimit = newLimit;
}
public static void updateMinTopup(double newTopup)
{
minTopup = newTopup;
}
}
////////MAIN METHOD////////////////////////
public class Test
{
public static void main(String[] args) {
String menuItems[] = {"1. Top up account ", "2. Pay for meal ", "3. Display Account Status",
"4. Display Account Balance ", "5. Display Account Details ",
"6. Update credit limit ", "7. Update Minimum top-up ", "8. Exit program"};
Menu myMenu = new Menu("Holiday Account", menuItems) ;
int choice;
Scanner keyb = new Scanner(System.in);
choice = myMenu.getChoice() ;
do{
choice = myMenu.getChoice();
//CanteenAcc Employee = new CanteenAcc("A01PL", "Patrick", 2);
CanteenAcc Employee2 = new StaffAccount("blah", "blah", 0.25);
switch (choice)
{
case 1 : System.out.println("How much would you like to top-up: ");
double deposit = keyb.nextDouble();
Employee2.topUp(deposit);
System.out.println("Your balance is: £" + Employee2.getBalance());
break ;
case 2: System.out.println("Input how much your meal costs: ");
try {
double amount = keyb.nextDouble();
Employee2.payForMeal(amount);
System.out.println("Your meal cost: " + amount);
} catch(Exception ex)
{
System.out.println(ex.toString());
}
System.out.println("Your balance is: £" + Employee2.getBalance());
break ;
case 3: System.out.println(Employee2.getStatus());
break;
case 4: System.out.println("£" + Employee2.getBalance());
break;
case 5: System.out.println(Employee.displayAccountDetails());
break;
case 6: System.out.println("What amount would you like the new limit to be: ");
double newLimit = keyb.nextDouble();
CanteenAcc.updateCreditLimit(newLimit);
System.out.println("The new credit limit is: " + newLimit);
case 7: System.out.println("What amount would you like the new limit to be: ");
double newMinTopup = keyb.nextDouble();
CanteenAcc.updateMinTopup(newMinTopup);
System.out.println("The new minimum topUp is: " + newMinTopup);
case 8: System.exit(0);
}
}//End DoWhile
while(choice != 8);
}
}
////STAFF ACCOUNT///////
public class StaffAccount extends CanteenAcc
{
private double discountRate;
public StaffAccount(String newId, String newName, double discountRate)
{
super (newId, newName);
this.discountRate = 0.25;
balance = 0;
}
public void setDiscountRate(double rate)
{
discountRate = rate;
}
public double getDiscountRate()
{
return discountRate;
}
public void payForMeal(double amount) throws Exception
{
amount = amount/discountRate;
super.payForMeal(amount);
}
}
OK:
You've got a CanteenAcc: good. You've also got a StaffAccount that inherits from CanteenAcc. Also good.
You should annotate StaffAccount.payForMeal() with #Override: When do you use Java's #Override annotation and why?
Your variable names should all start with lower case, e.g. CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);.
updateCreditLimit() and updateMinTopup() should NOT be static (because each different object might have a different value): Java: when to use static methods
... Finally ...
With CanteenAcc employee = new CanteenAcc("A01PL", "Patrick", 2);, then employee.payForMeal() will have the "CanteenAcc" behavior.
With CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);, then employee2.payForMeal() will have the "StaffAccount" behavior.
Q: So what's the problem? Does that help clarify ... or does it just confuse things further?
There are a number of things "wrong" with the code you posted. I hope you have an IDE, and step through the debugger with sample test values.
But to your original question:
You're on the right track.
There are a couple of "minor" issues I noted above.
I'm not sure why you're worried about "constructors". The way object oriented languages (like Java) work - if you define the right base classes, and appropriately "specialize" behavior in subclasses, then - through the magic of "inheritence" - everything "just works".
I modified your code slightly, and wrote a different "test driver". Here is the code, and the output:
StaffAccount.java
package com.example;
public class StaffAccount extends CanteenAccount {
private double discountRate;
public StaffAccount(String newId, String newName, double discountRate) {
super(newId, newName);
this.discountRate = discountRate; // Set this to "discountRate", instead of hard-coding 0.25
// You'll note that "balance" is implicitly set to "0.0" in the base class
}
public void setDiscountRate(double rate) {
discountRate = rate;
}
public double getDiscountRate() {
return discountRate;
}
#Override
public void payForMeal(double amount) throws Exception {
amount = amount / discountRate;
super.payForMeal(amount);
}
}
TestAccount.java
package com.example;
/**
* Test driver
* In a "real" application, I would implement these as a suite of JUnit tests
*/
public class TestAccount {
private static void buyAMeal (CanteenAccount person, double cost) {
try {
person.payForMeal(cost);
} catch (Exception e) {
System.out.println ("ERROR: " + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println (">>Creating employee (\"CanteenAccount\" and employee2 (\"StaffAccount\") objects...");
CanteenAccount employee = new CanteenAccount("A01PL", "Patrick", 2);
CanteenAccount employee2 = new StaffAccount("blah", "blah", 0.25);
System.out.println (">>Checking initial balances...");
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
System.out.println (">>Buying a $5.00 meal...");
System.out.println (" employee...");
buyAMeal (employee, 5.00);
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2...");
buyAMeal (employee2, 5.00);
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
System.out.println (">>Add $5.00 and buy another $5.00 meal...");
System.out.println (" employee...");
employee.topUp(5.0);
buyAMeal (employee, 5.00);
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2...");
employee2.topUp(5.0);
buyAMeal (employee2, 5.00);
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
}
}
Sample output:
>>Creating employee ("CanteenAccount" and employee2 ("StaffAccount") objects...
>>Checking initial balances...
employee balance=2.0, creditLimit=5.0
employee2 balance=0.0, creditLimit=5.0
>>Buying a $5.00 meal...
employee...
ERROR:
-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------
employee balance=-3.0, creditLimit=5.0
employee2...
ERROR:
------------------------------
Cost exceeds the credit limit.
------------------------------
employee2 balance=0.0, creditLimit=5.0
>>Add $5.00 and buy another $5.00 meal...
employee...
ERROR:
-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------
employee balance=-3.0, creditLimit=5.0
employee2...
ERROR:
------------------------------
Cost exceeds the credit limit.
------------------------------
employee2 balance=5.0, creditLimit=5.0
Having trouble compiling these two files to run together.
I get a "can't find or load main class" error or a "erroneous tree" error.
Never asked for help on here before, hope this works :)
package savingsaccount;
import java.util.Scanner;
public class SavingsAccount
{
public static void main(String[] args)
{
double begginingBalance, deposit, withdraw;
int months;
double monthlyRate;
double plus = 0.0;
double minus = 0.0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the balance at beggining of " +
"accounting period.");
begginingBalance = keyboard.nextDouble();
System.out.println("Please enter number of months in current " +
"accounting period.");
months = keyboard.nextInt();
System.out.println("Enter the annual interest rate.");
monthlyRate = keyboard.nextDouble();
a7main accounting = new a7main();
for(int month = 1; month<=months; month++)
{
System.out.println("Enter the amount of deposits for month " +
month + " : ");
plus = keyboard.nextDouble();
accounting.deposits(plus);
System.out.println("Enter the amount of withdrawals for" +
" month " + month + ": ");
minus = keyboard.nextDouble();
accounting.withdrawals(minus);
accounting.interest(monthlyRate);
}
System.out.println("The account balance is: " +
accounting.getBalance());
System.out.println("The total amount of deposits is:" + plus);
System.out.println("The total amount of withdrwals is: " + minus);
System.out.println("The earned interest is: " +
accounting.getRate());
}
}
HERE IS THE CLASS FILE
I am trying to use the methods in this file to calculate and hold the values from the other file.
public class a7main
{
private double totalBalance;
private double interestRate;
public a7main(double balance,double rate)
{
totalBalance = balance;
interestRate = rate;
}
public void deposits(double deposit)
{
totalBalance = totalBalance+deposit;
}
public void withdrawals(double withdraw)
{
totalBalance = totalBalance-withdraw;
}
public void interest(double rate)
{
interestRate = totalBalance*rate;
}
public double getBalance()
{
return totalBalance;
}
public double getRate()
{
return interestRate;
}
}
#Alex Goad -
Add package name in a7main class
You have created parameterized constructor and no default constructor.
a7main accounting = new a7main();
The above line will look for default constructor like
public a7main(){
}
this is my first question on the site. I am a fresh CS student needing some help with something that is probably really simple. The code as is will compile. When I enter in the values as the program asks, it stores the values wrong. It will store the right values for gross pay and savings rate but the IRA rate comes back as 100% even when entered at 6.9 and it seems it stores the IRA rate in saveAmount. Please halp me figure out what I am doing wrong here.
import java.text.DecimalFormat;
import java.util.*;
public class CollinDunn_1_05 {
static Scanner console = new Scanner(System.in);
static DecimalFormat formatCash = new DecimalFormat("#,###.00");
static double iraTotal = 0.0;
static double saveAmount = 0.0;
static double totalSave = 0.0;
static String line = "";
public static void main (String [] args) {
// Input variables
double grossPay = 0.0; // The gross pay from a users paycheck
double saveRate = 0.0; // This is the user entered savings rate
double iraRate= 0.0; // The IRA investment rate
String whichOne = ""; // A temp variable to pass a string type into UserInput
printInfo();
grossPay = userInput("gross pay");
saveRate = userInput("savings rate");
iraRate = userInput("IRA rate");
iraTotal = iraAmount(grossPay, iraRate);
saveAmount = savingsAmount(grossPay, saveRate);
outputResults(grossPay, saveRate, saveAmount, iraRate, iraTotal);
return;
} // End Main
public static void printInfo() {
System.out.println ("This program uses methods to calculate \n"
+ "savings amounts and IRA investment amounts \n"
+ "from user input consisiting of their gross pay, \n"
+ "their desired savings rate and IRA rate, made by "
+ " Collin Dunn");
return;
} // End ProgramInfo
public static double userInput(String whichOne) {
double saveMe = 0.0;
System.out.print("Please enter your " + whichOne + ": ");
saveMe = console.nextDouble();
return saveMe;
} // End userInput
public static double iraAmount(double grossPay, double iraRate) {
iraTotal = grossPay * (iraRate / 100.0);
return iraTotal;
} // End iraAmount
public static double savingsAmount(double grossPay, double saveRate) {
saveAmount = grossPay * (saveRate / 100.0);
return saveAmount;
} // End savingsAmount
public static void outputResults(double grossPay, double saveRate, double iraRate,
double saveAmount, double iraTotal) {
totalSave = saveAmount + iraTotal;
System.out.print ("With a gross pay of $" + formatCash.format(grossPay)
+ ", a savings rate of %" + formatCash.format(saveRate)
+ " and a IRA rate of %" +formatCash.format(iraRate)
+ ".\n Your savings amount will be $" + formatCash.format(saveAmount)
+ ", with a investment amount of $" + formatCash.format(iraTotal)
+ ".\n Which leaves you with a total savings of $" +
+ totalSave + ". Way to go for paying yourself!" );
return;
} // End outputResults
} //End Class
Your only issue is the order of arguments you pass to or have set on the outputResults() method.
Change the signature of the method to:
public static void outputResults(double grossPay, double saveRate, double saveAmount, double iraRate, double iraTotal) {
Which now matches how you call the method:
outputResults(grossPay, saveRate, saveAmount, iraRate, iraTotal);
Let me make a couple of additonal suggestions:
1) You are consistently naming arguments in your method signatures the same names as global variables, which makes it confusing which is which when accessing the variable in the method. Either avoid using the same names for the method input variables, or use something like this.amount = amount to make it more obvious of your intention.
2) Avoid static unless you have a valid reason to use it (which is pretty rare).
Instead, take advantage of Java's Object oriented nature and create an instance of your class in the main method and call methods on that instance. This will make your code more readable, reliable, and reusable.
3) In a method that returns type 'void', you don't need to add the empty return; statement.
To correct your issue and also demonstrate the points I listed, I have refactored your code and provided it below. By the way, you have a lot of potential. Despite the fact there are a few details you can improve, for being a first year CS student, your code is well written and thought out. Good job!
import java.text.DecimalFormat;
import java.util.*;
public class CollinDunn_1_05 {
DecimalFormat formatCash = new DecimalFormat("#,###.00");
double iraTotal = 0.0;
double saveAmount = 0.0;
double totalSave = 0.0;
double grossPay = 0.0; // The gross pay from a users paycheck
double saveRate = 0.0; // This is the user entered savings rate
double iraRate= 0.0; // The IRA investment rate
public CollinDunn_1_05(double gross, double saveRt, double iraRt){
this.grossPay = gross;
this.saveRate = saveRt;
this.iraRate = iraRt;
}
public void calculate(){
calcIraAmount();
calcSavingsAmount();
}
public static void main (String [] args) {
Scanner scanner = new Scanner(System.in);
printInfo();
CollinDunn_1_05 program = new CollinDunn_1_05(
userInput("gross pay", scanner),
userInput("savings rate", scanner),
userInput("IRA rate", scanner)
);
program.calculate();
program.outputResults();
} // End Main
public static void printInfo() {
System.out.println ("This program uses methods to calculate \n"
+ "savings amounts and IRA investment amounts \n"
+ "from user input consisiting of their gross pay, \n"
+ "their desired savings rate and IRA rate, made by "
+ " Collin Dunn");
return;
} // End ProgramInfo
public static double userInput(String whichOne, Scanner console) {
double saveMe = 0.0;
System.out.print("Please enter your " + whichOne + ": ");
saveMe = console.nextDouble();
return saveMe;
} // End userInput
public void calcIraAmount() {
iraTotal = grossPay * (iraRate / 100.0);
} // End iraAmount
public void calcSavingsAmount() {
saveAmount = grossPay * (saveRate / 100.0);
} // End savingsAmount
public void outputResults() {
totalSave = saveAmount + iraTotal;
System.out.print ("With a gross pay of \$" + formatCash.format(grossPay)
+ ", a savings rate of %" + formatCash.format(saveRate)
+ " and a IRA rate of %" +formatCash.format(iraRate)
+ ".\n Your savings amount will be \$" + formatCash.format(saveAmount)
+ ", with a investment amount of \$" + formatCash.format(iraTotal)
+ ".\n Which leaves you with a total savings of \$" +
+ totalSave + ". Way to go for paying yourself!" );
} // End outputResults
} //End Class
import java.util.Scanner;
public class ParadiseInfo2
{
public static void main(String[] args)
{
double price;
double discount;
double savings;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter cutoff price for discount >>");
price = keyboard.nextDouble();
System.out.print("Enter discount rates as a whole number >> ");
discount = keyboard.nextDouble();
System.out.println("Special this week on any service over " +
price);
System.out.println("Discount of " + discount + " percent");
System.out.println("That's a savings of at least $" + savings);
displayInfo();
savings = computeDiscountInfo(price, discount);
}
public static void displayInfo()
{
System.out.println("Paradise Day Spa wants to pamper you.");
System.out.println("we will make you look good.");
}
public static double computeDiscountInfo(double pr, double dscnt)
{
double savings;
savings = pr * dscnt / 100;
return savings;
}
}
I keep getting the following error on the above code. I can't figure out how to fix it. Thanks for all of your help!
ParadiseInfo2.java:18: error: variable savings might not have been
initialized
System.out.println("That's a savings of at least $" + savings);
The last line of main sets savings but you use it before then to print it. Change it to something like
// System.out.println("That's a savings of at least $" + savings);
displayInfo();
savings = computeDiscountInfo(price, discount);
System.out.println("That's a savings of at least $" + savings);
Having problems in my while loop. I'm getting a
Exception in thread "main" java.util.NoSuchElementException: No line found.
at java.util.Scanner.nextLine(Scanner.java:1516)
at Payroll.main(Payroll.java:70)`
Here's the code:
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.io.*;
import java.util.Scanner;
public class Payroll
{
public static void main(String[] args) throws IOException //throws exceptions
{
//Declare variables
String fileInput; // To hold file input
String fileOutput; // To hold file output
String date; // To hold the date
String userInput; // To hold user input from JOptionPane
String employeeID = ""; // To hold employee ID
String employeeName = ""; // To hold employee name
double hours = 0.0; // To hold employee hours
double wageRate = 0.0; // To hold employee wage rate
double taxRate = 0.0; // To hold employee tax rate
double taxWithheld; // To hold employee taxes withheld
double grossPay; // To hold employee gross pay
double netPay; // To hold employee net pay
double totalGross = 0.0; // To hold total gross pay
double totalTax = 0.0; // To hold total tax withheld
double totalNet = 0.0; // To hold total net pay
DecimalFormat money = new DecimalFormat("#,##0.00");// used to format money later on
date = JOptionPane.showInputDialog("Enter pay period ending date (mm/dd/yyyy): "); //hold user input into date
//Open the input file
File file = new File("EmployeeList.txt");
if (!file.exists())// check to see if the file exists
{
JOptionPane.showMessageDialog(null, "The file EmployeeList.txt is not found.");
System.exit(0);
}
// Create Scanner object to enable reading data from input file
Scanner inputFile = new Scanner(file);
// Create FileWriter and PrintWriter objects to enable
// writing (appending not overwriting) data to text file
FileWriter fwriter = new FileWriter("PastPayrolls.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);
outputFile.println("PAY PERIOD ENDING DATE: " + date);
while (inputFile.hasNext())
{
employeeID = inputFile.nextLine(); // Read info from first line and store it in employeeID
employeeName = inputFile.nextLine(); // Read info from next line and store it in employeeName
userInput = JOptionPane.showInputDialog("Employee Name: " +
employeeName +
"\nEnter number of" + // display employee name and ask for number of hours worked
" hours worked:");
hours = Double.parseDouble(userInput); // Store user's parsed input into hours
wageRate = inputFile.nextDouble(); // Read info from next line and store it in wageRate
taxRate = inputFile.nextDouble(); // Read info from next line and store it in taxRate
inputFile.nextLine(); // Read blank line
Paycheck paycheck = new Paycheck(employeeID, employeeName, wageRate, taxRate, hours);
paycheck.calcWages();
outputFile.println("Employee ID: " + paycheck.getEmployeeID());
outputFile.println("Name: " + paycheck.getEmployeeName());
outputFile.println("Hours Worked: " + hours);
outputFile.println("Wage Rate: $" + money.format(paycheck.getWageRate()));
outputFile.println("Gross Pay: $" + money.format(paycheck.getGrossPay()));
outputFile.println("Tax Rate: " + paycheck.getTaxRate());
outputFile.println("Tax Withheld: $" + money.format(paycheck.getTaxWithheld()));
outputFile.println("Net Pay: $" + money.format(paycheck.getNetPay()));
JOptionPane.showMessageDialog(null, "Employee ID: " + paycheck.getEmployeeID() +
"\nName: " + paycheck.getEmployeeName() +
"\nHours Worked: " + hours +
"\nWage Rate: $" + money.format(paycheck.getWageRate()) +
"\nGross Pay: $" + money.format(paycheck.getGrossPay()) +
"\nTax Rate: " + paycheck.getTaxRate() +
"\nTax Withheld: $" + money.format(paycheck.getTaxWithheld()) +
"\nNet Pay: $" + money.format(paycheck.getNetPay()));
totalGross += paycheck.getGrossPay();
totalTax += paycheck.getTaxWithheld();
totalNet += paycheck.getNetPay();
inputFile.nextLine();
}
}// end while loop
JOptionPane.showMessageDialog(null, "Total Pay Period Gross Payroll: $" + money.format(totalGross) +
"Total Pay Period Period Tax Withheld: $" + money.format(totalTax)+
"Total Pay Period Net Payroll: $" + money.format(totalNet));
outputFile.println();
outputFile.println("TOTAL PAY PERIOD GROSS PAYROLL: $" + money.format(totalGross));
outputFile.println("TOTAL PAY PERIOD TAX WITHHELD: $" + money.format(totalTax));
outputFile.println("TOTAL PAY PERIOD NET PAYROLL: $" + money.format(totalNet));
inputFile.close();
outputFile.close();
}
}'
Here is the other code containing my paycheck class:
`public class Paycheck
{
//Declare variables
private final String EMPLOYEE_ID; // Employee ID
private final String EMPLOYEE_NAME; // Employee Name
private final double WAGE_RATE; // Wage Rate
private final double TAX_RATE; // Tax Rate
private final double HOURS_WORKED; // Hours Worked
private double grossPay; // Gross Pay
private double taxWithheld; // Tax Withheld
private double netPay; // Net Pay
// Constructor
Paycheck(String id, String name, double wage, double tax, double hours)
{
EMPLOYEE_ID = id;
EMPLOYEE_NAME = name;
WAGE_RATE = wage;
TAX_RATE = tax;
HOURS_WORKED = hours;
}
public void calcWages()//calculates wages
{
grossPay = HOURS_WORKED * WAGE_RATE;
taxWithheld = grossPay * TAX_RATE;
netPay = grossPay - taxWithheld;
}//end calcWages
public String getEmployeeID()//returns Employee's ID
{
return EMPLOYEE_ID;
}//end getEmployeeID
public String getEmployeeName()//returns Employee's name
{
return EMPLOYEE_NAME;
}//end getEmployeeName
public double getWageRate()//returns Employee's wage rate
{
return WAGE_RATE;
}//end getWageRate
public double getTaxRate()//returns Employee's tax rate
{
return TAX_RATE;
}//end getTaxRate
public double getHoursWorked()//returns Employee's hours worked
{
return HOURS_WORKED;
}//end getHoursWorked
public double getGrossPay()//returns Employee's gross pay
{
return grossPay;
}//end getGrossPay
public double getTaxWithheld()//returns Employee's tax withheld
{
return taxWithheld;
}//end getTaxWithheld
public double getNetPay()//returns Employee's net pay
{
return netPay;
}//end getNetPay
}`
Sorry for the lengthy code. I figured someone might need a good majority of the code to figure out what was going wrong. If there are better ways of doing things as far as using better methods, I am forced to stick to simplicity, so please try and work within the realms of this code. I am a beginner in Java btw.
Thanks!
I'm guessing it's because you have:
while (inputFile.hasNext())
Use Scanner.hasNextLine.
Edit:
I tested your code with your sample input. I see what you mean now.
while ( inputFile.hasNextLine() ) {
employeeID = inputFile.nextLine(); // Read info from first line and store it in employeeID
employeeName = inputFile.nextLine(); // Read info from next line and store it in employeeName
userInput = JOptionPane.showInputDialog( "Employee Name: " + employeeName + "\nEnter number of" + // display employee name and ask for number of hours worked
" hours worked:" );
hours = Double.parseDouble( userInput ); // Store user's parsed input into hours
wageRate = inputFile.nextDouble(); // Read info from next line and store it in wageRate
taxRate = inputFile.nextDouble(); // Read info from next line and store it in taxRate
Using hasNextLine as your condition will only ensure that the next call to nextLine will be valid. But, your calling nextLine twice, and then calling nextDouble after that. You can either (1) ensure that the calls your making match up with the file exactly, or (2) check that there is a next token every time you call next. I think (1) is your problem.
I was able to fix your program with the following:
while ( inputFile.hasNextLine() ) {
employeeID = inputFile.nextLine();
employeeName = inputFile.nextLine();
userInput = JOptionPane.showInputDialog( "Employee Name: " + employeeName + "\nEnter number of hours worked:" );
hours = Double.parseDouble( userInput );
wageRate = Double.parseDouble(inputFile.nextLine());
taxRate = Double.parseDouble(inputFile.nextLine());
Paycheck paycheck = new Paycheck( employeeID, employeeName, wageRate, taxRate, hours );
paycheck.calcWages();
JOptionPane.showMessageDialog( null, "Employee ID: " +
paycheck.getEmployeeID() + "\nName: " +
paycheck.getEmployeeName() + "\nHours Worked: " +
hours + "\nWage Rate: $" +
money.format( paycheck.getWageRate() ) + "\nGross Pay: $" +
money.format( paycheck.getGrossPay() ) + "\nTax Rate: " +
paycheck.getTaxRate() + "\nTax Withheld: $" +
money.format( paycheck.getTaxWithheld() ) + "\nNet Pay: $" +
money.format( paycheck.getNetPay() ) );
}
The file contents:
00135
John Doe
10.50
0.20
00179
Mary Brown
12.50
1.20