Char match that is not exact still works - java

I am sorry to post again so soon, but I ran into another error in my Tax program. My program is only supposed to work if someone enters only 's,' 'S,' 'm,' 'M,' 'c,' or 'C' for the marital status. When I entered anything that does not start with one of those letters, it prints Invalid Entry, like it is supposed to, but when I enter something that starts with an upper/lowercase s, m, or c, it proceeds as if I only entered that first letter. How do I make it so that the program only proceeds if you enter the one letter?
Thanks!!
Here is my code:
import java.util.Scanner;
public class TaxPrep
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char maritalStatus;
double grossIncome = 0;
double numberOfExemptions = 0;
double taxRate = 0;
double taxableIncome = 0;
double taxesOwed = 0;
String anotherCustomer = "y";
System.out.print("A A R O N ' S T A X P R E P A R E R\n\n");
do{
System.out.print("Are you (s)ingle, (m)arried, or (c)ohabiting?\n");
System.out.print("Enter s, m, or c ==> ");
maritalStatus = sc.next().charAt(0);
switch (maritalStatus)
{
case 's': case 'S':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 20;
break;
case 'm': case 'M':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 25;
break;
case 'c': case 'C': //tax rate for cohabiting depends on taxable income
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
if (taxableIncome <= 20_000)
{
taxRate = 10;
break;
}
else if (taxableIncome <= 50_000)
{
taxRate = 15;
break;
}
else
{
taxRate = 30;
break;
}
default: //if input for marital status is invalid
System.out.print("\nInvalid entry.\n");
continue;
}
taxesOwed = taxableIncome * (taxRate / 100);
//taxable income and taxes owed cannot be negative
if (taxableIncome < 0)
{
taxableIncome = 0;
}
if (taxesOwed < 0)
{
taxesOwed = 0;
}
//tax summary
System.out.print("\nINCOME TAX SUMMARY");
System.out.print("\ntax rate: " + taxRate + "%");
System.out.print("\ntaxable income: $" + taxableIncome);
System.out.print("\ntaxes owed: $" + taxesOwed);
//would you like to process another customer?
System.out.print("\n\nProcess another customer? (y/n): ");
anotherCustomer = sc.next();
System.out.print("\n");
} while (anotherCustomer.equalsIgnoreCase("y")); //as long as user enters 'y' or 'Y', the program will continue to calculate the income tax summary
}
}

You are testing only the first character, even if the entered word is longer:
maritalStatus = sc.next().charAt(0);
sc.next() returns a String, and charAt(0) returns just its first character. So if you entered "sFoo", maritalStatus would just be 's' and the "Foo" would be ignored.
You should get the whole entered String (and possibly convert it to upper case for easier comparison in the switch). The variable maritalStatus should be declared as String in this case:
maritalStatus = sc.next().toUpperCase();
switch (maritalStatus) {
case "S":
//...
}
Switch statement works with Strings, unless you are using Java 6 or older. In that case you would use:
maritalStatus = sc.next().toUpperCase();
if (maritalStatus.equals("S")) {
//...
} else if...

Related

Java Income Tax Calculator Need to add error message for any number that is 0 or less

I have a java project that is a Income tax calculator, and I am supposed to add a error message to it so that the program will not respond to a number that is 0 or less in the income prompt. I am just not sure where to put the prompt or what type of error message I need to accomplish this. Code:
import java.util.Scanner;
public class TaxCalculator {
static void calculate() {
// The tax rates for different types of customers.
final double RATE1 = 0.20;
final double RATE2 = 0.25;
final double RATE3 = 0.10;
final double RATE4 = 0.15;
final double RATE5 = 0.30;
final double RATE1_SINGLE_LIMIT = 1;
final double RATE2_MARRIED_LIMIT = 1;
final double RATE3_COHABITATING_LIMIT = 20000;
final double RATE4_COHABITATING_LIMIT = 50000;
double tax = 0;
Scanner in = new Scanner(System.in);
//Prompt for user to enter the customers income
System.out.print("Enter customer's income: ");
double income = in.nextDouble();
in.nextLine();
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus = in.next();
in.nextLine();
// Where the taxes are calculated
if (maritalStatus.equals("s") && income > RATE1_SINGLE_LIMIT) {
tax = RATE1 * income;
} else if (maritalStatus.equals("m") && income > RATE2_MARRIED_LIMIT) {
tax = RATE2 * income;
} else if (maritalStatus.equals("c") && income <= RATE3_COHABITATING_LIMIT) {
tax = RATE3 * income;
} else if (maritalStatus.equals("c") && income <= RATE4_COHABITATING_LIMIT) {
tax = RATE4 * income;
} else {
tax = RATE5 * income;
}
System.out.print("Your income tax is: $" + tax);
}
// asks user if they would like to process another customer.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String newResponse = "";
do {
calculate();
System.out.println();
System.out.println("Process another response?. Please enter 'y' for yes, or 'n' for no: ");
newResponse = in.next();
in.nextLine();
} while (newResponse.equals("y"));
}
}
You could add the loops after printing appropriate prompts:
System.out.print("Enter customer's income: ");
double income;
while ((income = in.nextDouble()) <= 0) {
System.out.print("Income " + income + " is invalid. Please input correct income which must be greater than 0: ");
in.nextLine();
}
System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus;
while (!(maritalStatus = in.next()).matches("[smc]")) {
System.out.print("Marital status " + maritalStatus + " is invalid. Please input correct value: 's', 'm', or 'c': ");
in.nextLine();
}
Output:
Enter customer's income: -12
Income -12.0 is invalid. Please input correct income which must be greater than 0: -23
Income -23.0 is invalid. Please input correct income which must be greater than 0: 2300
Please enter 's' for single, 'm' for married, or 'c' for cohabitating: 1
Marital status 1 is invalid. Please input correct value: 's', 'm', or 'c': m

There is an error in my java coding when I put a grade percentage for my gradebook application

I have an application that acts as a gradebook. However, in the console log when I type in a grade there seems to be an error. I was hoping someone could fix this to where I am able to put in a grade percentage and the error does not pop up.enter code here
Below is what the error says:java.lang.NumberFormatException: For input string: "70%"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Gradebook.getScores(Gradebook.java:45)
at Gradebook.main(Gradebook.java:154)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Here is my code:
import java.util.Scanner;
public class Gradebook {
//getNumStudents takes a Scanner object as parameter
//the reader object lets us take user input
public static int getNumStudents(Scanner reader){
int numStudents = 0;
//we get the number of students
do{
System.out.print("Enter number of students: ");
numStudents = Integer.parseInt(reader.nextLine());
//we determine if the user input is valid
//it should be greater than 0
//because we don't want the number o students to be negative
//if it is not valid then we keep taking inputs
if(numStudents > 0){
break;
}else{
System.out.println("Please enter atleast 1 student.");
}
}while(true);
System.out.println("================================================================================================================================================");
//we return numStudents
return numStudents;
}
//getScores takes our Scanner object again and the number student as parameter this time
public static String[] getScores(Scanner reader, int numStudents){
//we create an array of string studInfo
//that will be returned containing the name, and scores of our students
String[] studInfo = new String[numStudents];
String name = "";
int quiz = 0;
int assign = 0;
int test1 = 0;
int test2 = 0;
//we use a for loop to keep taking student scores
for(int i = 0; i < numStudents; i++){
//enter name
System.out.print("Enter student "+(i+1)+" name: ");
name = reader.nextLine();
//enter quiz, assignment, test1 and test2 scores
//we also validate scores to not be negative
//and not out of bounds
do{
System.out.print("Enter Quiz Score (over 40): ");
quiz = Integer.parseInt(reader.nextLine());
if(quiz >= 0 && quiz <= 40){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Assignment Score (over 30): ");
assign = Integer.parseInt(reader.nextLine());
if(assign >= 0 && assign <= 30){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Midterm Test Score (over 55): ");
test1 = Integer.parseInt(reader.nextLine());
if(test1 >= 0 && test1 <= 55){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Final Test Score (over 65): ");
test2 = Integer.parseInt(reader.nextLine());
if(test2 >= 0 && test2 <= 65){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
//after we get the name and student's score
//we put it in a string
studInfo[i] = name+ " " +quiz+ " " +assign+ " " +test1+ " " +test2;
System.out.println();
}
//return the studInfo
return studInfo;
}
//our displayGrade takes String array as parameter
public static void displayGrade(String[] studInfo){
//this is our header for our formatted table
System.out.println("================================================================================================================================================");
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10s%-15s%s", "Name", "Quiz", "Assignment", "Midterm Test", "Final Test", "Average", "Letter Grade", "Status"));
System.out.println("================================================================================================================================================");
//we go through our array of string
for(int i = 0; i < studInfo.length; i++){
//the split method returns an array of strings
//that are split by a delimeter
String[] data = studInfo[i].split(" ");
//we sum up the scores
//but we have to parse it to double first
//to get the closest sum
double sum = ((Double.parseDouble(data[1]) / 40.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[2]) / 30.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[3]) / 55.0) * 100.0) * 0.3;
sum += ((Double.parseDouble(data[4]) / 65.0) * 100.0) * 0.4;
//after that we round the sum and convert it to int and put it in average
int average = (int) Math.round(sum);
char letterGrade = ' ';
//we get the letter grade using a nested if else
if(average>=0 && average<=59){
letterGrade = 'F';
}else if(average>=60 && average<=69){
letterGrade = 'D';
}else if(average>=70 && average<=79){
letterGrade = 'C';
}else if(average>=80 && average<=89){
letterGrade = 'B';
}else if(average>=90 && average<=100){
letterGrade = 'A';
}
String status = "";
//we determine the status of our student here
//using switch case
//if the leter grade is f then he fails
//if the case is D then he needs to go to remedial class
//otherwise they pass
switch(letterGrade){
case 'F':
status = "Fail";
break;
case 'D':
status = "Remedial";
break;
case 'A': case 'B': case 'C':
status = "Pass";
break;
}
//we displat student information
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10d%-15c%s", data[0], data[1], data[2], data[3], data[4], average, letterGrade, status));
}
System.out.println("================================================================================================================================================");
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
displayGrade(getScores(reader, getNumStudents(reader)));
}
}
Instead of nextLine() you can use next("[0-9]+%?") and then remove the optional % character:
public static int getNumStudents(Scanner reader) {
int numStudents = 0;
//we get the number of students
do {
System.out.print("Enter number of students: ");
// Read the number either with or without the % sign
String input = reader.next("[0-9]+%?");
if (input.endsWith("%")) {
// Remove the % sign if present
input = input.substring(0, input.length() - 1);
}
numStudents = Integer.parseInt(input);
// we determine if the user input is valid
// it should be greater than 0
// because we don't want the number o students to be negative
// if it is not valid then we keep taking inputs
if (numStudents > 0) {
break;
}
System.out.println("Please enter at least 1 student.");
} while (true);
System.out.println("================================================================================================================================================");
// we return numStudents
return numStudents;
}

Input Validation Java

I am pretty new to Java. I am doing a program that calculates an Income Tax summary based on one's marital status. My program works, aside from one problem: my input validation section for the marital status is not working properly. When I enter something other than s, S, m, M, c, and C, the program is supposed to perform input validation for that, but currently, when I enter something like x, it skips the gross income and exemptions, and spits out that tax rate, taxes owed, and taxable income are all 0.
EDIT: Sorry if that was confusing. Basically, if the user uses invalid input, and the user then enters something valid, I want to know how to make it go back to the beginning of the switch statement to determine the tax rate Any help would be appreciated!
import java.util.Scanner;
public class TaxPrep
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char maritalStatus;
double grossIncome = 0;
double numberOfExemptions = 0;
double taxRate = 0;
double taxableIncome = 0;
double taxesOwed = 0;
String anotherCustomer = "y";
System.out.print("_ _ _ _ _ ' S T A X P R E P A R E R\n\n");
do{
System.out.print("Are you (s)ingle, (m)arried, or (c)ohabiting?\n");
System.out.print("Enter s, m, or c ==> ");
maritalStatus = sc.next().charAt(0);
switch (maritalStatus)
{
case 's': case 'S':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 20;
break;
case 'm': case 'M':
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
taxRate = 25;
break;
case 'c': case 'C': //tax rate for cohabiting depends on taxable income
System.out.print("Gross income ==> ");
grossIncome = sc.nextDouble();
System.out.print("Number of exemptions ==> ");
numberOfExemptions = sc.nextInt();
taxableIncome = grossIncome - (1000 * numberOfExemptions);
if (taxableIncome <= 20_000)
{
taxRate = 10;
break;
}
else if (taxableIncome <= 50_000)
{
taxRate = 15;
break;
}
else
{
taxRate = 30;
break;
}
default: //if input for marital status is invalid
do{ //continues to ask for valid input until user inputs a valid marital status
System.out.print("\nInvalid entry.");
System.out.print("\nAre you (s)ingle, (m)arried, or (c)ohabiting?");
System.out.print("\nEnter s, m, or c ==> ");
maritalStatus = sc.next().charAt(0);
} while (maritalStatus != 's' && maritalStatus != 'S' && maritalStatus != 'm' && maritalStatus != 'M' && maritalStatus != 'c' && maritalStatus != 'C');
}
taxesOwed = taxableIncome * (taxRate / 100);
//taxable income and taxes owed cannot be negative
if (taxableIncome < 0)
{
taxableIncome = 0;
}
if (taxesOwed < 0)
{
taxesOwed = 0;
}
//tax summary
System.out.print("\nINCOME TAX SUMMARY");
System.out.print("\ntax rate: " + taxRate + "%");
System.out.print("\ntaxable income: $" + taxableIncome);
System.out.print("\ntaxes owed: $" + taxesOwed);
//would you like to process another customer?
System.out.print("\n\nProcess another customer? (y/n): ");
anotherCustomer = sc.next();
System.out.print("\n");
} while (anotherCustomer.equalsIgnoreCase("y")); //as long as user enters 'y' or 'Y', the program will continue to calculate the income tax summary
}
}
Instead of retrying after
default: //if input for marital status is invalid
do{ //continues to ask for valid input until user inputs a valid marital status
} while(...);
simply skip to the end of the outer loop:
default:
System.out.print("\nInvalid entry.");
continue;
You need to have the switch-Statement inside the do-while-loop you got in default in your example, like
boolean martialStatusValid = true
maritalStatus = sc.next().charAt(0);
do {
martialStatusValid = true;
switch (maritalStatus) {
//your cases here
default:
martialStatusValid = false;
//display some kind of error message ...
}
} while (! martialStatusValid)
That way, as long as the martialStatus is invalid the User will be prompted for new input and the switch will repeat.
One thing to note abound Launes "continue-solution: that will start the next iteration of the outer do-loop, so basically restart your Program. Might not be what you're after if you have more Sections with user input, f.e. if you want to ask for sex etc.

Calculating Areas of Geometric Figures using multiple methods in Java

My program will calculate the area but I need to have each different shape in it's own method and I'm having difficulty understanding how to first separate them all into their own method and link them all together. Any help is much appreciated.
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "Please choose which area/volume to calculate: 1-Circle 2-Triangle 3-Cone 4-Cylinder 5-Sphere 6-Quit: ";
System.out.print(s);
System.out.println(" ");
int num = keyboard.nextInt();
if (num < 1 || num > 6){
System.out.print("Please choose a number between 1 and 6: ");
num = keyboard.nextInt();
}
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 2){
System.out.print("Please enter the base: ");
double b = keyboard.nextDouble();
double at;
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
at = .5 * b * h;
System.out.print("The area of the triangle is: " + at);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 3){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double v1;
v1 = (1/3) * 3.14 * r * r * h;
System.out.print("The volume of the cone is: " + v1);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 4){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
System.out.print("Please enter the height: ");
double h = keyboard.nextDouble();
double vc;
vc = 3.14 * r * r * h;
System.out.print("The volume of the cylinder is: " + vc);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 5){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double vs;
vs = (4/3) * 3.14 * r * r * r;
System.out.print("The volume of the sphere is: " + vs);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
if(num == 6){
System.out.print("Thank you for using this program");
}
}
}
You can use switch..case
switch(num) {
case 1: calculateCircleArea();
break;
case 2: calculateTriangleArea();
break;
case 3: calculateConeVolume();
break;
case 4: calculateCylinderVolume();
break;
case 5: calculateSphereVolume();
break;
case 6: System.out.print("Thank you for using this program");
break;
default: System.out.print("Please choose a number between 1 and 6: ");
break;
}
You can create new private/public methods to do the calculations and seperate them.
Take this part
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = 3.14 * r * r;
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
You can create a new method for the calculation like so
public static double getArea(double radius)
{
return 3.14*radius*radius;
}
Then, inside your if statement you can say
if(num == 1){
System.out.print("Please enter the radius: ");
double r = keyboard.nextDouble();
double a;
a = getArea(r);
System.out.print("The area of the circle is: " + a);
System.out.println(" ");
System.out.print(s);
num = keyboard.nextInt();
}
you see in this case, you get a one-line method which isn't very usefull. But you can split off more extensive calculations as well, this is just as an example. In addition, instead of all the if-blocks, you can use a switch statement like the other answer shows you.

Java Bank Program has a weird ghost loop?

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.

Categories