I'm having some trouble with a part of an assignment. I have to see how many times an employee is processed in my program, after the loop runs once it asks the user if they would like to process another. If they enter y for yes and then they enter n for end after the second employee calculation. I want it to say "Number of employees processed: 2". How could I do this?
package paytime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String firstName, lastName, choice;
double hoursWorked, hourlyWage;
boolean processAnotherEmployee = true;
Employee one = new Employee();
while(true)
{
if (processAnotherEmployee)
{
System.out.print("Enter Y to process employee or any other key to end: ");
choice = scn.next();
if (choice.equalsIgnoreCase("Y"))
{
System.out.print("Enter employee number: ");
int number = scn.nextInt();
while (!one.findEmpNumber(number))
{
System.out.print("Invlaid, enter a proper employee number: ");
number = scn.nextInt();
}
System.out.print("Enter first name: ");
firstName = scn.next();
System.out.print("Enter last name: ");
lastName = scn.next();
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextDouble();
while (hoursWorked < 0)
{
System.out.print("Negative hours not allowed. Enter hours worked: ");
hoursWorked = scn.nextDouble();
}
System.out.print("Enter hourly wage: $");
hourlyWage = scn.nextDouble();
while (hourlyWage < 0 || hourlyWage > 100)
{
System.out.print("Negative wage is not allowed or wage entered is to high. Enter hourley wage: $");
hourlyWage = scn.nextDouble();
}
double overtimeHours = hoursWorked - 40;
double overtimeWage = hourlyWage * 1.5;
System.out.println(" ");
if (hoursWorked <= 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
}
else if (hoursWorked > 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
System.out.println(" ");
System.out.println("Worker " + number + " Overtime Calculation: ");
System.out.println("Overtime Pay is: " + one.callOvertimePay(overtimeHours, overtimeWage, hourlyWage, hoursWorked));
System.out.println("Overtime Income Tax is: " + one.callOvertimeTax());
System.out.println("Overtime Net Pay is: " + one.callOvertimeNetPay());
System.out.println("Total Net Pay is: " + one.callTotalNetPay());
System.out.println(" ");
}
}
else if (!choice.equalsIgnoreCase("Y"))
{
processAnotherEmployee = false;
System.out.println("Total number of Employees processed: ");
System.out.println(" ");
System.out.println("End of program");
break;
}
}
}
}
}
and
package paytime;
public class Employee {
private int empNumbers [] = {101, 103, 106, 109, 110, 113, 116, 118, 120};
public double weeklyPay, hoursWorked, hourlyWage, incomeTax, netPay,
overtimePay, overtimeHours, overtimeWage, overtimeIncomeTax,
overtimeNetPay, totalNetPay;
public boolean findEmpNumber(int number)
{
boolean found = false;
for (int sub = 0; sub < empNumbers.length; sub++)
{
if (number == empNumbers[sub])
{
found = true;
break;
}
}
return found;
}
private void calculateWeeklyPay(double hoursWorked, double hourlyWage) {
if (hoursWorked > 40)
{
hoursWorked = 40;
weeklyPay = hoursWorked * hourlyWage;
}
else
{
weeklyPay = hoursWorked * hourlyWage;
}
}
public double callWeeklyPay(double hoursWorked, double hourlyWage) {
calculateWeeklyPay(hoursWorked, hourlyWage);
return weeklyPay;
}
private void calculateIncomeTax() {
if (weeklyPay > 0.0 && weeklyPay <= 300.0)
{
incomeTax = weeklyPay * 0.10;
}
else if (weeklyPay > 300.1 && weeklyPay <= 400.0)
{
incomeTax = weeklyPay * 0.12;
}
else if (weeklyPay > 400.1 && weeklyPay <= 500.0)
{
incomeTax = weeklyPay * 0.15;
}
else if (weeklyPay > 500.1)
{
incomeTax = weeklyPay * 0.20;
}
}
public double callIncomeTax() {
calculateIncomeTax();
return incomeTax;
}
private void calculateNetPay() {
netPay = weeklyPay - incomeTax;
}
public double callNetPay() {
calculateNetPay();
return netPay;
}
private void calculateOvertimePay(double overtimeHours, double overtimeWage, double hourlyWage, double hoursWorked) {
overtimePay = overtimeHours * overtimeWage;
}
public double callOvertimePay(double overtimeHours, double overtimeWage, double hourlyWage, double hoursWorked) {
calculateOvertimePay(overtimeHours, overtimeWage, hourlyWage, hoursWorked);
return overtimePay;
}
private void calculateOvertimeTax() {
overtimeIncomeTax = overtimePay * 0.25;
}
public double callOvertimeTax() {
calculateOvertimeTax();
return overtimeIncomeTax;
}
private void calculateOvertimeNetPay() {
overtimeNetPay = overtimePay - overtimeIncomeTax;
}
public double callOvertimeNetPay() {
calculateOvertimeNetPay();
return overtimeNetPay;
}
private void calculateTotalNetPay() {
totalNetPay = netPay + overtimeNetPay;
}
public double callTotalNetPay() {
calculateTotalNetPay();
return totalNetPay;
}
}
You can achieve this by simply having "int employeesProcessed = 0;" outside of you while loop then add "employeesProcessed++;" directly after "if (choice.equalsIgnoreCase("Y"))" so that each time your program is asked to process an employ you add 1 to your int that is keeping track of how many employees you have processed. Then you can add this variable onto the end of your printed string so it says "Total number of Employees processed: " + employeesProcessed.
Related
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 5 years ago.
Improve this question
Output Error :
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of expression
I'm creating a class that calculate 1 student that take 3 quizzes 25%, 1 Midterm 25% , and 1 Final 50%
package Grading;
import java.util.Scanner;
public class Grading {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
public static double quiz1, quiz2, quiz3, midterm, finalExam, Grades, totalGrade, bothQuizzes, PfinalExam, PmidTerm;
public static String studentname;
public static int Score;
public String getstudentname( )
{
return studentname;
}
public double getquiz1()
{
return quiz1;
}
public double getquiz2 ()
{
return quiz2;
}
public double getquiz3 ()
{
return quiz3;
}
public double midterm()
{
return midterm;
}
public double finalExam()
{
return finalExam;
}
public void setquiz1 (double quiz1)
{
this.quiz1 = quiz1;
}
public void setquiz2 (double quiz2)
{
this.quiz2 = quiz2;
}
public void setquiz3 (double quiz3)
{
this.quiz3 = quiz3;
}
public void setmidterm()
{
this.midterm = midterm;
}
public void setfinalExam()
{
this.finalExam = finalExam;
}
public void setGrades ()
{
}
public String toString(){
return this.quiz1 + " " + this.quiz2 + this.quiz3 + " " + this.midterm + " " + this.finalExam;
}
public static void readInput(){
System.out.println("Please enter the grade you got for the first quiz: ");
quiz1 = grades.nextInt();
while (quiz1 <0 || quiz1>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz1 = grades.nextInt();
}
System.out.println("Please enter the grade you got for the second quiz: ");
quiz2 = grades.nextInt();
while (quiz2 <0 || quiz2>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz2 = grades.nextInt();
}
System.out.println("Please enter the grade you got for the third quiz: ");
quiz3 = grades.nextInt();
while (quiz3 <0 || quiz3>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz3 = grades.nextInt();
}
System.out.println("Please enter the grade you got on your midterm: ");
midterm = grades.nextInt();
while (midterm <0 || midterm>100)
{
System.out.println("Please enter a grade between 0 and 100: ");
midterm = grades.nextInt();
}
System.out.println("Please enter the grade you got on your final exam: ");
finalExam = grades.nextInt();
while (finalExam < 0 || finalExam > 100)
{
System.out.println("Please enter a grade between 0 and 100: ");
finalExam = grades.nextInt();
}
}
public static void output()
{
System.out.println(" your score for the first quiz was " + quiz1 );
System.out.println("your score for the second quiz was " + quiz2);
System.out.println("your score for the third quiz was " + quiz3);
System.out.println(" your score for the midterm was " + midterm );
System.out.println("your score for the final exam was " + finalExam);
bothQuizzes = ((quiz1 + quiz2 + quiz3)/100)*.25;
PmidTerm = (midterm/100) *.35;
PfinalExam = (finalExam/100) * .40;
System.out.println("Your total grade for these grades is " + totalGrade + "%");
System.out.println("Your total grade for these grades is " + totalGrade);
double letterGrade = totalGrade;
if (letterGrade >= 90)
{
System.out.println("Your grade is an A");
// grade = "A";
}
else if (letterGrade >= 80)
{
System.out.println("Your grade is a B");
}
else if (letterGrade >= 70)
{
System.out.println("Your grade is a C");
}
else if (letterGrade >= 60)
{
System.out.println("Your grade is a D");
}
else
{
System.out.println("Your grade is an F");
}
}}
I have re-written your program. I hope that this is what you wanted to achieve. I didn't know how you wanted to count the grade, so I've marked the place where you can change that code with a comment.
Since there were some major problems in your code with field declaration and function bodies, I've reorganized them. You can take a look at this code:
import java.util.Scanner;
public class Grading {
private int quiz1, quiz2, quiz3, midterm, finalExam; //quizzes exams tests what grades
public void readInput () {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the grade you got for the first quiz: ");
quiz1 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got for the second quiz: ");
quiz2 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got for the third quiz: ");
quiz3 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got on your midterm: ");
midterm = readInt(in, 0, 100);
System.out.print("Please enter the grade you got on your final exam: ");
finalExam = readInt(in, 0, 100);
}
public void output () {
System.out.println("Your score for the first quiz was " + quiz1);
System.out.println("Your score for the second quiz was " + quiz2);
System.out.println("Your score for the third quiz was " + quiz3);
System.out.println("Your score for the midterm was " + midterm);
System.out.println("Your score for the final exam was " + finalExam);
//dunno if this is the way you want to count it; change as needed
double quizzes = (quiz1 + quiz2 + quiz3) / 100 * 0.25;
double Pmidterm = midterm / 100 * 0.25;
double PfinalExam = finalExam /100 * 0.50;
double totalGrade = (quizzes + Pmidterm + PfinalExam) * 100.0;
char grade;
if (totalGrade >= 90)
grade = 'A';
else if (totalGrade >= 80)
grade = 'B';
else if (totalGrade >= 70)
grade = 'C';
else if (totalGrade >= 60)
grade = 'D';
else grade = 'F';
System.out.printf("Your grade is %c\n", grade);
}
private int readInt (Scanner in, int min, int max) {
int value = in.nextInt();
if (value < min || value > max) {
System.out.printf("Please enter a grade between %d and %d: ", min, max);
return readInt(in, min, max);
}
return value;
}
public static void main(String[] args) {
Grading grading = new Grading();
grading.readInput();
grading.output();
}
}
You never closed your main function
I am getting an error on this program for some reason and I have no idea what it means. I tried googling around, but nothing related to my issue is coming up. Does this have to do with an IOException by any chance? Also, where does the input get stored? In the class file? For example: if I was to input money into the account, would the inputed value be saved in a different file, or does the fact that I made an array of 30 account for a double amount of all 30 objects created?
Main class:
import java.util.Scanner;
import java.text.NumberFormat;
public class Account2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Account[] acct = new Account[30];
System.out.println("Enter your account number (1-30): ");
int key = scan.nextInt() - 1;
int reset = 0;
while (reset == 0)
{
System.out.println("Enter W for withdrawl; D for deposit; X to escape");
char choice = scan.next().charAt(0);
if (choice == 'W' || choice == 'w' || choice == 'D' || choice == 'd' || choice == 'x' || choice == 'X')
{
if (choice == 'W' || choice == 'w')
{
System.out.println("Enter amount to withdraw: ");
Double withdraw1 = scan.nextDouble();
if (withdraw1 <= acct[key].getBalance())
{
acct[key].withdraw(withdraw1);
System.out.println("User # " + key++ + " funds after withdraw: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Insufficient funds.");
}
if (choice == 'D' || choice == 'd')
{
System.out.println("Enter amount to deposit: ");
Double deposit1 = scan.nextDouble();
if (deposit1 > 0)
{
acct[key].deposit(deposit1);
System.out.println("User # " + key++ + " funds after deposit: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Use the withdrawl feature to withdrawl money.");
}
if (choice == 'x' || choice == 'X')
System.out.println("Thank You for using this bank.");
reset++;
}
else
{
System.out.println("Invalid entry, please try again");
reset = 0;
}
}
}
}
Second Class:
import java.text.NumberFormat; //links to Part2
public class Account
{
private final double RATE = 0.03; //Interest is 3%
private long acctNumber;
private double balance;
private String name;
//Defines owner, account number, and initial balance.
public Account(String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//deposits a specified amount and returns new balance
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//withdraws the specified amount from the account and applies the fee
// + returns balance
public double withdraw(double amount)
{
int fee = 1;
balance = balance - amount - fee;
return balance;
}
//Adds interest to the account
public double addInterest()
{
balance += (balance * RATE);
return balance;
}
public double getBalance()
{
return balance;
}
//returns a one line description of the account as a string
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "/t" + name + "/t" + fmt.format(balance);
}
}
Error message:
Enter your account number (1-30):
5
Enter W for withdrawl; D for deposit; X to escape
d
Enter amount to deposit:
50
Exception in thread "main" java.lang.NullPointerException
at Account2.main(Account2.java:40)
You're trying to acces an index of acct but the array is empty Account[] acct = new Account[30];
You should first fill the array, try to make the user create an account first.
I am still having trouble figuring out how the heck the most efficient way to do this is.. Basically, I am trying to make the balance = 0 for every object in the Account array created. I tried using a for loop and set balance = 0for each account created, but I am unsure of how to make this work since the balance variable is created in the class that has all of the methods. I have been trying to this problem all day, but no luck. Thanks.
Main method:
import java.util.Scanner;
import java.text.NumberFormat;
public class Account2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Account[] acct = new Account[30];
for (int count2; count2 < 30; count2++)
{
balance = 0; //Initial balance is always set to zero to be able to run fresh program every time
}
System.out.println("Enter your account number (1-30): ");
int key = scan.nextInt() - 1;
int reset = 0;
while (reset == 0)
{
System.out.println("Enter W for withdrawl; D for deposit; X to escape");
char choice = scan.next().charAt(0);
if (choice == 'W' || choice == 'w' || choice == 'D' || choice == 'd' || choice == 'x' || choice == 'X')
{
if (choice == 'W' || choice == 'w')
{
System.out.println("Enter amount to withdraw: ");
Double withdraw1 = scan.nextDouble();
if (withdraw1 <= acct[key].getBalance())
{
acct[key].withdraw(withdraw1);
System.out.println("User # " + key++ + " funds after withdraw: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Insufficient funds.");
}
if (choice == 'D' || choice == 'd')
{
System.out.println("Enter amount to deposit: ");
Double deposit1 = scan.nextDouble();
if (deposit1 > 0)
{
acct[key].deposit(deposit1);
System.out.println("User # " + key++ + " funds after deposit: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Use the withdrawl feature to withdrawl money.");
}
if (choice == 'x' || choice == 'X')
System.out.println("Thank You for using this bank.");
reset++;
}
else
{
System.out.println("Invalid entry, please try again");
reset = 0;
}
}
}
}
Supporting class:
public class Account
{
private final double RATE = 0.03; //Interest is 3%
private int acctNumber;
private String name;
private balance;
//Defines owner, account number, and initial balance.
public Account(String owner, int account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//deposits a specified amount and returns new balance
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//withdraws the specified amount from the account and applies the fee
// + returns balance
public double withdraw(double amount)
{
int fee = 1;
balance = balance - amount - fee;
return balance;
}
//Adds interest to the account
public double addInterest()
{
balance += (balance * RATE);
return balance;
}
public double getBalance()
{
return balance;
}
//returns a one line description of the account as a string
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "/t" + name + "/t" + fmt.format(balance);
}
}
From an outside class, you can only interact with Account in the way exposed in its visible (e.g. public) API.
In this case, the current way to do this would be to withdraw() the current balance:
acct[i].withdraw(acct[i].getBalance());
Though this specific case would put the balance into the negatives because you charge a fee for a withdrawal (which is hidden from the calling class).
If you were to expose a setBalance method on Account, you could instead do
acct[i].setBalance(0);
However on closer look, it seems like what you are having trouble with is actually initializing the array of accounts. You can do this like this:
for (int count2; count2 < 30; count2++)
{
acct[count2] = new Account(owner, count2, 0);
}
So I have been trying to figure this out for the past 5 hours and the reason being...from a beginner point of view this code looks fine with no errors but the output is still wrong...basically for every 10 kids tickets the user gets one free,so the output is fine if the free tickets is less than the adults but it subtracts the extra adults when its the other way around.
package theatre;
import java.util.*;
public class Theatre {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the number of tickets you would like to buy for each type: ");
System.out.println("Adult: £10.50");
System.out.println("Child: £7.30");
System.out.println("Concessions £8.40");
System.out.println("Adult: ");
int Adult = kybd.nextInt();
System.out.println("Child: ");
int Child = kybd.nextInt();
System.out.println("Concessions: ");
int concessions = kybd.nextInt();
int freeAdult = Child / 10;
if (freeAdult < 9) {
System.out.println("You get " + freeAdult + " adult tickets");
} else {
System.out.println("You don't get any free tickets");
}
System.out.println(freeAdult); //reference out
double adultBill = (Adult * 10.50) - (freeAdult * 10.50);
double childBill = Child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
double totalBill2 = childBill + concessionsBill;
System.out.println(totalBill2); //reference out
if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
} else {
System.out.println("Please enter a corrrect value");
}
}
}
Thanks
I think you have your logic a little confused:
int freeAdult = Child / 10;
if (freeAdult < 9) {
System.out.println("You get " + freeAdult + " adult tickets");
} else {
System.out.println("You don't get any free tickets");
}
appears to be calculating how many free adult tickets the person gets based on the number of child tickets (Child / 10) ...but is then saying they get no tickets if they've qualified for more than 10? I think you might be using the wrong variable here. Then:
double adultBill = (Adult * 10.50) - (freeAdult * 10.50);
double childBill = Child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
double totalBill2 = childBill + concessionsBill;
System.out.println(totalBill2); //reference out
if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
} else {
System.out.println("Please enter a corrrect value");
}
I believe is meant to calculate 2 bills, one including adults and one not and then if the number of free adult tickets is greater than the number of adults, discard the first bill and use the second (which never included the adults calculation), in which case you have your if statement the wrong way around, it should be:
if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
...however you should only have to calculate one bill by simply changing the adult calculation to:
double adultBill = freeAdult < Adult ? (Adult * 10.50) - (freeAdult * 10.50) : 0;
Then calculate bill as normal:
double totalBill = adultBill + childBill + concessionsBill;
System.out.printf("Total bill is: £%.2f\n", totalBill);
public class Theatre {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the number of tickets you would like to buy for each type: ");
System.out.println("Adult: £10.50");
System.out.println("Child: £7.30");
System.out.println("Concessions £8.40");
System.out.println("Adult: ");
int adult = kybd.nextInt();
System.out.println("Child: ");
int child = kybd.nextInt();
System.out.println("Concessions: ");
int concessions = kybd.nextInt();
int freeAdult = child / 10;
System.out.println("You get " + freeAdult + " adult tickets free");
if(adult >0){
adult = adult - freeAdult;
}
double adultBill = (adult * 10.50);
double childBill = child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
System.out.printf("Total bill is: £%.2f\n", totalBill);
}
}
I cannot figure this problem out. Everything in the program works the way i want it to except after i use the 'o' open account option, 'w' withdrawal accout options.. etc that after completion, repeats the loop as desired, but returns the else line "Command was not recognized; please try again." and then reprints the menu. If i use the 's' command it works fine. i removed the "balance = input.nextDouble();" line and it works correctly, but i can't figure out why it returns the else statement and reprints.
import java.util.Scanner;
import java.text.*;
public class Bank
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
String eol = System.getProperty("line.separator");
DecimalFormat df = new DecimalFormat("0.00");
int numAccounts = 1;
String number = "None Selected";
String userInput;
double balance = 0;
double amount = 0;
int i = 0;
int j;
BankAccount[] accounts = new BankAccount [100];
accounts[0] = new BankAccount (number, balance);
String BBalance = df.format(accounts[i].getBalance());
while (1 < 2){
if (numAccounts == accounts.length){
BankAccount[] tempArray = new BankAccount[accounts.length * 2];
for (int k = 0; k < accounts.length; k++){
tempArray[k] = accounts[k];
}
accounts = tempArray;
}
try{
System.out.print ( eol +
"-----------------------------------------------------" + eol +
"|Commands: o - Open account c - Close account|" + eol +
"| d - Deposit w - Withdraw |" + eol +
"| s - Select account q - Quit |" + eol +
"-----------------------------------------------------" + eol +
"Current account: " + accounts[i].getNumber() + " Balance: $" + df.format(accounts[i].getBalance()) +
eol );
}
catch(java.lang.Throwable t) {
System.out.println("Account number was not found");
}
userInput = input.nextLine().trim().toLowerCase();
if (userInput.substring(0).equals("o")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
System.out.print("Enter Initial Balance: ");
balance = input.nextDouble();
accounts[numAccounts++] = new BankAccount (number, balance);
i = numAccounts - 1;
continue;
}
else if (userInput.substring(0).equals("d")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
System.out.print("Enter Amount To Deposit: ");
amount = input.nextDouble();
accounts[i].deposit(amount);
continue;
}
else if (userInput.substring(0).equals("s")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++){
if (accounts[i].getNumber().equals(number)){
break;
}
}
if (i != numAccounts){
System.out.print("Account number was not found");
}
continue;
}
else if (userInput.substring(0).equals("c")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
accounts[i] = accounts[--numAccounts];
continue;
}
else if (userInput.substring(0).equals("w")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
System.out.print("Enter Amount To Withdraw: ");
amount = input.nextDouble();
accounts[i].withdraw(amount);
continue;
}
else if (userInput.substring(0).equals("q")) {
System.exit(0);
}
else{
System.out.println("Command was not recognized; please try again.");
continue;
}
}
//System.out.print(userInput);
//System.out.print(accounts[0]);
}
}
Here's the BankAccount class:
public class BankAccount {
String number = "123-456";
double balance = 1.00;
public BankAccount(String accountNumber, double initialBalance){
number = accountNumber;
balance = initialBalance;
}
public void deposit (double amount){
balance += amount;
}
public void withdraw (double amount){
balance -= amount;
}
public String getNumber(){
return number;
}
public double getBalance(){
return balance;
}
BankAccount[] accounts = new BankAccount [100];
}
You're not skipping past the end of the lines when you're reading in the second numbers in the commands that require one.
Adding an input.nextLine() to those is one quick way around it (non I/O lines redacted).
// etc.
} else if (userInput.substring(0).equals("d")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
System.out.print("Enter Amount To Deposit: ");
amount = input.nextDouble();
input.nextLine();
continue;
} // etc.