Java Bank Program has a weird ghost loop? - java

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.

Related

How to loop a user input until integer is entered?

I want to run an interactive program where a user is prompted to enter a number of students. If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")
I have the following code:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
How can I create a loop for this?
Let's add a loop, take the value as String and check if it is a number:
String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
System.out.print("Enter the number of students: ");
sizeString = s.nextLine();
} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
Try catching the exception and handling it until you get the desired input.
int numberOfStudents;
while(true)
{
try {
System.out.print("Enter the number of student: ");
numberOfStudents = Integer.parseInt(s.next());
break;
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
try this
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
int no1 = 0;
Scanner scanner = new Scanner(System.in);
while(true)
{
try {
System.out.print("Number 1: ");
no1 = Integer.parseInt(scanner.next());
break;
}
catch(NumberFormatException e) {
System.out.println("..You have not entered valid value!");
}
}

Strings as sentinel values in a while loop

I'm trying to write a program that asks the user if they want to enter a real number. If yes, then prompt the user to enter a number. Keep prompting for number inputs until user says "no." Once this happens, output the average of the numbers entered.
I think I'm stuck trying to implement a string for the sentinel value. I want the sentinel value to be "no." But with this last attempt I have here, when I enter "yes" I get an InputMismatchException. Also, not sure if this is a job for do/while or just while. Kind of new to all this and not sure how to go about this, as we don't have examples of using strings for sentinels.
public static void main(String[] args) {
int count = 0;
float total = 0;
float inputNumber;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = "";
inputNumber = scan.nextFloat();
do {
reply = scan.nextLine();
if (reply.equalsIgnoreCase("yes")) {
System.out.println("Enter a number > ");
total+= inputNumber ;
count++ ;
System.out.println("Enter another number, or " +
"enter \"no\" to terminate > " );
inputNumber = scan.nextFloat();
}
}
while (! reply.equalsIgnoreCase("no")) ;
if (count != 0) {
System.out.println("The average of the numbers is " +
(total / count));
}
}
}
Remove first inputNumber = scan.nextFloat();
Fix loop.
Add scan.nextLine() after scan.nextFloat()
public static void main(String[] args) {
int count = 0;
float total = 0f;
float inputNumber = 0f;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = scan.nextLine();
while (reply.equalsIgnoreCase("yes")) {
System.out.println("Enter a number > ");
inputNumber = scan.nextFloat();
scan.nextLine();
total += inputNumber;
count++;
System.out.println("Enter another number, or enter \"no\" to terminate > ");
reply = scan.nextLine();
}
if (count != 0) {
System.out.println("The average of the numbers is " + (total / count));
}
}
EDIT
public static void main(String[] args) {
int count = 0;
float total = 0f;
float inputNumber = 0f;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = scan.nextLine();
if (!reply.equalsIgnoreCase("yes"))
return;
System.out.println("Enter a number > ");
while (!reply.equalsIgnoreCase("no")) {
reply = scan.nextLine();
try {
inputNumber = Float.parseFloat(reply);
} catch (NumberFormatException e) {
continue;
}
total += inputNumber;
count++;
System.out.println("Enter another number, or enter \"no\" to terminate > ");
}
if (count != 0) {
System.out.println("The average of the numbers is " + (total / count));
}
}

Program is not quitting when choice 2 is entered instead it is asking to enter a positive number. What is the issue here?

The program is not quitting when choice 2 is entered instead it's asking to enter a positive value. It should only ask that if the choice was 1 and then the number of rooms entered was less than one. It should immediately quit the program but it's not. What can I do to fix this? Is it because of braces missing or extra ones.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Paint {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
do {
displayMenu();
choice = keyboard.nextInt();
if (choice == 1) {
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
} while (choice != 2);
}
public static void displayMenu() {
System.out.println("1)Calculate Estimate");
System.out.println("2)Quit the program");
System.out.println("Please make a selection");
}
public static double numGallons(double sqr) {
return sqr / 115;
}
public static double numHours(double sqr) {
return (sqr / 115) * 8;
}
public static double laborCost(double cph, double nh) {
return cph * nh;
}
public static double paintCost(double ng, double cpg) {
return ng * cpg;
}
}
You should show the menu and get the choice before entering the loop, and at the end of the loop.
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
displayMenu();
choice = keyboard.nextInt();
while (choice != 2) {
//if (choice ==1)
//{
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
//}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
displayMenu();
choice = keyboard.nextInt();
}
}

How do I write a loop that prints the year and balance?

Scanner console = new Scanner(System.in);
System.out.println("Enter Starting Balance: ");
Double balance = Double.parseDouble(console.nextLine());
System.out.println("Enter Yearly Contribution: ");
Double cont = Double.parseDouble(console.nextLine());
System.out.println("Enter Average Return On Investment as %: ");
Double avg = Double.parseDouble(console.nextLine());
System.out.println("Enter Number of years: ");
int year = Integer.parseInt(console.nextLine());
double result1 = (balance + cont) * (1 + avg / 100);
double result2 = (result1 + cont) * (1 + avg / 100);
year = 0;
while (year <= year) {
System.out.println("Year " + year + ": " + balance + "");
year = year + 1;
for (result2 = result2; result2 >= result2; result2 = result2 + result2) {
}
//I am aware that the loop is wrong, just not sure the best way to write it.
So provided there isn't a whole lot of detail, I wrote this code which results in output very close to the example you provided. Modify it as needed to match your desired output.
package various;
import java.util.Scanner;
public class Balance {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Starting Balance: ");
double balance = sc.nextDouble();
System.out.println("Enter Yearly Contribution: ");
double cont = sc.nextDouble();
System.out.println("Enter Average Return On Investment as %: ");
double avg = sc.nextDouble();
System.out.println("Enter Number of years: ");
int years = sc.nextInt();
double temp = 0;
for(int i = 0; i <= years; i++) {
double result = balance + (i*cont)+ (i*temp*(avg/100));
temp = result;
System.out.println("Year "+i+": "+result);
}
sc.close();
}
}

Exception Handling for no user input in Java

I am trying to get my program to exception handle for if the user inputs nothing so they will get an error message of "Error, enter a dollar amount greater than 0" or "Error, Enter a 1, 2 or 3". As of now, the program does nothing if the user just hits "enter" with no input....
import java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Candleline
{
public static void main(String[] args)
{
//initiate scanner
Scanner input = new Scanner(System.in);
System.out.println("\tCandleLine - Candles Online");
System.out.println(" ");
//declare variables and call methods
double candleCost = getCandleCost();
int shippingType = getShippingType();
double shippingCost = getShippingCost(candleCost, shippingType);
output(candleCost, shippingCost);
}
public static double getCandleCost()
{
//get candle cost and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
double candleCost = 0;
while(!done)
{
System.out.print("Enter the cost of the candle order: ");
try
{
inputCost = input.next();
candleCost = Double.parseDouble(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (candleCost <=0) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
}
return candleCost;
}
public static int getShippingType()
{
//get shipping type and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
int shippingCost = 0;
while(!done)
{
System.out.println(" ");
System.out.print("Enter the type of shipping: \n\t1) Priority(Overnight) \n\t2) Express (2 business days) \n\t3) Standard (3 to 7 business days) \nEnter type number: ");
try
{
inputCost = input.next();
shippingCost = Integer.parseInt(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (shippingCost <=0 || shippingCost >= 4) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println(" ");
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
}
return shippingCost;
}
public static double getShippingCost(double candleCost, int shippingType)
{
//calculate shipping costs
double shippingCost = 0;
if (shippingType == 1)
{
shippingCost = 16.95;
}
if (shippingType == 2)
{
shippingCost = 13.95;
}
if (shippingType == 3)
{
shippingCost = 7.95;
}
if (candleCost >= 100 && shippingType == 3)
{
shippingCost = 0;
}
return shippingCost;
}
public static void output(double fCandleCost, double fShippingCost)
{
//display the candle cost, shipping cost, and total
Scanner input = new Scanner(System.in);
DecimalFormat currency = new DecimalFormat("$#,###.00");
System.out.println("");
System.out.println("The candle cost of " + currency.format(fCandleCost) + " plus the shipping cost of " + currency.format(fShippingCost) + " equals " + currency.format(fCandleCost+fShippingCost));
}
}
Replace input.next();
with input.nextLine();
You can write a method that validates the input before proceeding. It can keep asking for inputs if user enters something that is not valid. E.g. below example demonstrates how to validate an integer input:
private static int getInput(){
System.out.print("Enter amount :");
Scanner scanner = new Scanner(System.in);
int amount;
while(true){
if(scanner.hasNextInt()){
amount = scanner.nextInt();
break;
}else{
System.out.println("Invalid amount, enter again.");
scanner.next();
}
}
scanner.close();
return amount;
}

Categories