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 8 years ago.
Improve this question
I know these must be basic errors, but I'm not sure how to fix them.
I changed my class name to Interface & now Java has a problem with it.
Also, in my switch statement, I've tried to call the enterData method, but I'm getting an error on this line as well as on this line... "private static void enterData()" <-- it says a "token" is missing on this line?
I'm trying to call a method from case 0, but it isn't working.
import java.util.Scanner;
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
private static void enterData()
{
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
You can't define method in another method.
Change your code to this:
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private static void enterData()
{
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
Scanner console = new Scanner(System.in);
System.out.println("Product name between 3 & 10 characters long: ");
String name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Try making a separate method and make those fields global. Something like this
import java.util.Scanner;
public class Interface {
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
private void run() {
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
do {
System.out
.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch (option) {
case 0:
enterData(console);
break;
case 1:
break;
case 2:
break;
case 9:
System.out.println("You chose to exit the program.");
break;
default:
System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private void enterData(Scanner console) {
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out
.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Interface is some kind of an abstract class definition keyword in java.
You can use a keyword to name your class with capitalized letters, but seriously, don't do this.
And you are not calling a method, you are implementing it in another method. You should go over writing and calling a method in java once again ;)
Related
I am creating a basic banking app that tracks a user's bank account activities, and I cannot seem to figure out why when I run my code that it is simply running what I have set for the "default" case; so even when I press 1,2,3, or 4, the console states, "Error -- Please choose a valid option."
Thanks in advance!
package Account;
import java.util.Scanner;
public class Account extends Bank {
int Balance;
int Previoustransaction;
int amount;
int amount2;
String Name;
String ID;
Account(String Name,String ID){
}
void deposit(int amount) {
if (amount != 0) {
Balance+=amount;
Previoustransaction=amount;
}
}
void withdraw(int amount) {
if(amount!=0) {
Balance-=amount;
Previoustransaction = -amount;
}
}
void getPrevioustransaction() {
if(Previoustransaction > 0) {
System.out.println("Deposited:" + Previoustransaction);
}
else if(Previoustransaction<0) {
System.out.println("Withdrawn:" + Math.abs(Previoustransaction));
} else {
System.out.println("No transaction occurred.");
}
}
void Menu() {
int choice = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome," + Name + ".");
System.out.println("Your account number is" + ID);
System.out.println("What would you like to do?");
System.out.println("1.Check balance.");
System.out.println("2. Make a deposit.");
System.out.println("3. Make a withrawl.");
System.out.println("4. Show last transaction.");
System.out.println("0. Exit.");
do {
System.out.println("Choose an option.");
choice = scan.nextInt();
System.out.println();
switch(choice) {
case'1':
System.out.println("Balance = $" + Balance);
System.out.println();
break;
case'2':
System.out.println("Enter an amount to deposit.");
int amount = scan.nextInt();
deposit (amount);
System.out.println();
break;
case'3':
System.out.println("Enter an amount to withdrawl.");
int amount2 = scan.nextInt();
withdraw(amount2);
break;
case '4':
getPrevioustransaction();
break;
case '0':
break;
default:
System.out.println("Error -- Please choose a valid option.");
}
} while (choice != 0);
System.out.println("Thank you for using the Bank Account Tracker!");
scan.close();
}
{
}
{
}
}
The reason your program isn't working as you expect is that:
you are prompting for user input
capturing that input as a numeric value; specifically, primitive data type int
comparing that int input against various character values – that is, values of primitive data type ch (such as '1')
Here's a paired down version of what you're doing:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case '1':
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
Here's that same block, but instead of case '1' (which matches on a single character value), I changed it to case 1 (which matches on an integer value):
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1: // <-- this is the only edit, use 1 instead of '1'
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
So, to fix your program, change your various case statements to use integer values, not characters.
I am currently making a simple ATM program in java.
I want to write a while loop where when user enters wrong pin it will prompt the user to enter again until the pin is matched. When the pin is matched, it will display the main menu.
I tried by myself, but I don't know how to fix it.
while(userPIN != savedPIN)
{
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
int pass = again.nextInt();
break;
}
Remove the `break;' statement and update userPIN with the new pin as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int savedPIN = 4444;
Scanner input = new Scanner(System.in);
System.out.println("Enter password");
int userPIN = input.nextInt();
double withdraw = 0.0, amount = 0.0, deposit = 0.0;
while (userPIN != savedPIN) {
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
userPIN = again.nextInt();
}
while (userPIN == savedPIN) {
System.out.println(" 1 - Inquire Balance \n 2 - Withdraw \n 3 - Deposit \n 0 - Quit ");
Scanner inputNum = new Scanner(System.in);
int number = inputNum.nextInt();
switch (number) {
case 1:
System.out.println("The current balance is $" + amount);
break;
case 2:
System.out.println("Enter the amount to withdraw : ");
withdraw = input.nextDouble();
if (amount >= withdraw) {
amount = amount - withdraw;
System.out.println("The current balance is $" + amount);
} else {
System.out.println("Insufficient balance");
}
break;
case 3:
System.out.println("Enter the amount to deposit : ");
deposit = input.nextDouble();
amount = amount + deposit;
System.out.println("The current balance is $" + amount);
break;
case 0:
System.exit(4);
}
}
}
}
Ok 2 errors:
1)you test userPIN != savedPIN but you accept the value into variable pass with which you do nothing.
2)remove the break in the first loop it will always exit without looping.
it should look like :
while(pass!= savedPIN)
{
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
int pass = again.nextInt();
}
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;
}
I'm working on a program for a plant nursery that has two classes; PlantNursery and Plant. The user gets promoted 4 questions. 1) Add a plant, 2) List all the plants, 3) Edit a plant, and 4) Quit. I got 1, 2, and 4 working fine. My problem lies within option 3. I display the current list of plants in the array and ask the user to pick one by it's common name. Then I store the String and compare it with an if statement. The if statement is not working as expected. I get the error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at plantnursery.PlantNursery.main(PlantNursery.java:92)
C:\Users\diggz\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 52 seconds)
Plant class:
package plantnursery;
public class Plant
{
//Variables
private String commonName, scientificName;
private double maxHeight, price;
private boolean fragile;
//Constructor
public Plant(String commonName, String scientificName, double maxHeight,
double price, boolean fragile)
{
this.maxHeight = maxHeight;
this.price = price;
this.commonName = commonName;
this.scientificName = scientificName;
this.fragile = fragile;
}
public double getMaxHeight()
{
return maxHeight;
}
public void setMaxHeight(double maxHeight)
{
this.maxHeight = maxHeight;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
public String getCommonName()
{
return commonName;
}
public void setCommonName(String commonName)
{
this.commonName = commonName;
}
public String getScientificName()
{
return scientificName;
}
public void setScientificName(String scientificName)
{
this.scientificName = scientificName;
}
public boolean isFragile()
{
return fragile;
}
public void setFragile(boolean fragile)
{
this.fragile = fragile;
}
#Override
public String toString() {
return "Plant{" + "commonName= " + commonName + ", scientificName= "
+ scientificName + ", maxHeight= " + maxHeight + ", price= "
+ price + ", fragile= " + fragile + '}';
}
}
PlantNursery class:
package plantnursery;
import java.util.ArrayList;
import java.util.Scanner;
public class PlantNursery
{
public static void main(String[] args)
{
//Variables to hold user input.
double userHeight, userPrice;
String userComName, userSciName, blankLine;
boolean userFragile;
int ans, choice;
//Reference variable to an object.
Plant p;
//Scanner for user input.
Scanner scan = new Scanner(System.in);
//ArrayList to store all the plants in.
ArrayList<Plant> plantList = new ArrayList<>();
//While loop asking the user to create new plants and store them
//in the the ArrayList. Edit any of the plants already in the ArrayList
//or quit the program.
while(true)
{
//Ask the user what they want to do.
System.out.println("What do you want to do?\n1. Add a plant. "
+ "\n2. List all plants.\n3. Edit a plant. \n4. Quit.");
//Store answer
ans = scan.nextInt();
//Choice 1. Add a new plant into the ArrayList.
if(ans == 1)
{
//Get rid of buffer overflow from int ans.
blankLine = scan.nextLine();
//Ask the user for input for a new plant object.
System.out.println("Please enter the common name of the plant:");
userComName = scan.nextLine();
System.out.println("Please enter the scienitific name of the plant: ");
userSciName = scan.nextLine();
System.out.println("Please enter the maximum height (in feet) of the plant: ");
userHeight = scan.nextDouble();
System.out.println("Please enter the price of the plant: ");
userPrice = scan.nextDouble();
System.out.println("Please enter if the plant is fragile (true or false): ");
userFragile = scan.nextBoolean();
//Create the new plant object.
p = new Plant(userComName, userSciName, userHeight, userPrice,
userFragile);
//Add the plant object to the ArrayList.
plantList.add(p);
}
//Choice 2. Display all plant(s) in the ArrayList.
if(ans == 2)
{
//List all the current plants in the ArrayList.
for(Plant curList : plantList)
{
System.out.println(curList);
}
}
//Choice 3. Edit information on plant(s) in ArrayList.
if(ans == 3)
{
//Allows the user to edit until they wish to quit.
while(true)
{
//Counter for ArrayList
int i;
//String to hold which plant the user wishes to edit.
String userAns;
//Ask the user which plant they wish to edit.
System.out.println("Which plant to wish to edit (choose the common name)?");
//Display the plant(s).
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
//Get the user input and compare it to the Common Name
blankLine = scan.nextLine();
userAns = scan.nextLine();
if(userAns.equalsIgnoreCase(plantList.get(i).getCommonName())) //PROBLEM CODE
{
//Ask what the user wishes to edit.
System.out.println("What do you wish to edit?\n1. Common Name."
+ "\n2. Scientific Name.\n3. Maximum Height.\n4. Price"
+ "\n5. Is it fragile (true or false)?\n6. Quit.");
//Get user choice.
choice = scan.nextInt();
//Choice 1
if(choice == 1)
{
System.out.println("What is the new Common Name? ");
String newComName = scan.nextLine();
plantList.get(i).setCommonName(newComName);
}
//Choice 2
if(choice == 2)
{
System.out.println("What is the new Scientific Name? ");
String newSciName = scan.nextLine();
plantList.get(i).setScientificName(newSciName);
}
//Choice 3
if(choice == 3)
{
System.out.println("What is the new Maximum Height? ");
double newHeight = scan.nextDouble();
plantList.get(i).setMaxHeight(newHeight);
}
//Choice 4
if(choice == 4)
{
System.out.println("What is the new Price?");
double newPrice = scan.nextDouble();
plantList.get(i).setPrice(newPrice);
}
//Choice 5
if(choice == 5)
{
System.out.println("Is the plant Fragile (true or false)? ");
boolean newFragile = scan.nextBoolean();
plantList.get(i).setFragile(newFragile);
}
//Choice 6
if(choice == 6)
{
break;
}
}
}
}
//Choice 4. End program.
if(ans == 4)
{
break;
}
}
}
}
Okay so I changed the third choice into a switch statement. Now the problem I have is I can only do one edit. After that first edit when I try to pick another plant or the same one to edit it doesn't read it and keeps asking me the same question.
Code:
//Choice 3. Edit information on plant(s) in ArrayList.
if(ans == 3)
{
OUTER:
while (true) {
int i;
String userAns;
System.out.println("Which plant to wish to edit (choose the common name)?");
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
blankLine = scan.nextLine();
userAns = scan.nextLine();
if (userAns.equalsIgnoreCase(plantList.get(i-1).getCommonName())) {
System.out.println("What do you wish to edit?\n1. Common Name."
+ "\n2. Scientific Name.\n3. Maximum Height.\n4. Price"
+ "\n5. Is it fragile (true or false)?\n6. Quit.");
choice = scan.nextInt();
//Choices
switch (choice)
{
//Choice 1
case 1:
System.out.println("What is the new Common Name? ");
blankLine = scan.nextLine();
String newComName = scan.nextLine();
plantList.get(i-1).setCommonName(newComName);
break;
//Choice 2
case 2:
System.out.println("What is the new Scientific Name? ");
blankLine = scan.nextLine();
String newSciName = scan.nextLine();
plantList.get(i-1).setScientificName(newSciName);
break;
//Choice 3
case 3:
System.out.println("What is the new Maximum Height? ");
double newHeight = scan.nextDouble();
plantList.get(i-1).setMaxHeight(newHeight);
break;
//Choice 4
case 4:
System.out.println("What is the new Price?");
double newPrice = scan.nextDouble();
plantList.get(i-1).setPrice(newPrice);
break;
//Choice 5
case 5:
System.out.println("Is the plant Fragile (true or false)? ");
boolean newFragile = scan.nextBoolean();
plantList.get(i-1).setFragile(newFragile);
break;
//Choice 6
case 6:
break OUTER;
default:
break;
}
}
}
}
ArrayList index starts with 0, so you have to do plantList.get(i-1).setPrice(newPrice);
You are starting index 0. So if you type 2 it means you trying to access 3 values
array[0], array[1], array[2].
Change for(i = 0; i < plantList.size(); i++)
to for(i = 1; i < plantList.size(); i++)
if you do not wish to change your for loop then you need to change plantList.get(i) to plantList.get(i-1) to make sure it is within the range
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
You've incremented i to plantList.size(). When you access the list with plantList.get(i).getCommonName(), i is already larger that the largest index.
You probably shouldn't use a variable defined outside the loop as the counter in the loop.
Have you considered a Map instead of seaching through the list?
I'm not very adept in getting the running totals using Java as I've started recently. I have to display and hold the running total of the bank balance and for some strange reason, it's resetting back to 100, which is what I declared it as to start with. Is there any way for me to stop the bank balance from being reset every time it loops?
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int choice, totBal = 0, totWith = 0, totDep = 0;
double with, remBal = 0, deposit, bankBal = 100;
char reply = 0;
do
{
System.out.println("");
System.out.println("Bank online\n");
System.out.println("1. Withdraw");
System.out.println("2. Deposit");
System.out.println("3. Balance");
System.out.println("4. Account Details");
System.out.println("5. Exit\n");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
if(choice == 1)
{
System.out.print("How much do you wish to withdraw?\n");
with = sc.nextInt();
remBal = bankBal - with;
System.out.println("Your new balance is: " + remBal);
totWith++;
}
else if(choice == 2)
{
System.out.print("How much do you wish to deposit?\n");
deposit = sc.nextInt();
remBal = remBal + deposit;
System.out.println("Your new balance is: " + remBal);
totDep++;
}
else if(choice == 3)
{
System.out.println("Your balance is: " + remBal);
totBal++;
}
else if(choice == 4)
{
System.out.println("You made " + totWith + " withdrawls from your account.");
System.out.println("You made " + totDep + " deposits to your account.");
System.out.println("You made " + totBal + " balance checks on your account.");
}
else if(choice == 5)
{
}
System.out.println("");
System.out.print("Do you want to enter another option?(y/n): ");
reply = sc.next().charAt(0);
}while(reply == 'Y' || reply == 'y');
System.out.println("Thank you and goodbye!");
}
}
Also, I feel that I have WAY too many variables. How can I cut back on these?
Your problem is with following statement:
double with, remBal = 0, deposit, bankBal = 100;
Here you are initialising remBal as 0, while when one deposits amount/checks balance you do:
remBal = remBal + deposit;//you use remBal for blaance check
So on first attempt it will try to add 0 with say $100 which will be 100 while bankBal is 100 it should be 100. So initialize remBal same as bankBal (or use just one variable for bankBalance i.e. either of one).
You set the bankBal value to 100 at the start of the program.
When doing withdrawals, you always do
remBal = bankBal - with
which will always equate to
remBal = 100 - with
since you never change bankBal to reflect the updated balance after each loop.
One approach to solve this is to remove the
bankBal
variable altogether and simply set your
remBal
variable to your desired starting value.
Finally change the withdrawal computation mentioned above to
remBal = remBal - with
One thing you can do is implement switch-cases to call methods specific to Depost, Withdraw, etc. An example of this roughly would be:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please Enter what you would like to do: ");
String enterPrompt = input.next();
int options = 5;
switch (options) {
case 1: enterPrompt = "Deposit";
doDeposit();
break;
case 2: enterPrompt = "Withdrawel";
doWithdrawel();
break;
case 3: enterPrompt = "Balance";
viewBalance();
break;
case 4: enterPrompt = "Account Details";
viewAccount();
break;
case 5: enterPrompt = "Exit";
System.exit(1);
break;
}
public void doDeposit(){
//local variables here
//Do stuff
}
public void doWithdrawel(){
//local variables here
//Do stuff
}
public void viewBalance(){
//local variables here
//Do stuff
}
public void viewAccount(){
//local variables here
//Do stuff
}
}