Do/while loop isn't executing properly - java

Im sure I am missing something simple but I cannot get my do while loop to execute properly. I want it to run through the first time and keep going until the user inputs q. It currently executes once and then loops back up to ask what account to access and then does nothing. Any help or pointing me in the right direction so I can fix it would be greatly appreciated.
public class Crawford_Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double input1;
String accountChoice;
String accountActivity;
RegularAccount regAcct = new RegularAccount(0, .5);
SavingsAccount savAcct = new SavingsAccount(0, .5);
do{
System.out.println("What account would you like to access(regular or savings)?" );
accountChoice = keyboard.nextLine();
if(accountChoice.equalsIgnoreCase("regular"))
System.out.println("What action do you wish to perform(deposit, withdraw or monthly process)? ");
accountActivity = keyboard.nextLine();
if (accountActivity.equalsIgnoreCase("deposit"))
{
System.out.println("How much would you like to deposit?");
input1= keyboard.nextDouble();
regAcct.deposit(input1);
System.out.println("Your balance is " + regAcct.getBalance() );
}
else if (accountActivity.equalsIgnoreCase("withdraw"))
{
System.out.println("How much would you like to withdraw?");
input1= keyboard.nextDouble();
regAcct.withdraw(input1);
System.out.println("Your balance is "+ regAcct.getBalance());
}
else if (accountActivity.equalsIgnoreCase("monthly process"))
{
regAcct.monthlyProcess();
}
else {
if (accountChoice.equalsIgnoreCase("savings"))
if (accountActivity.equalsIgnoreCase("deposit"))
{
System.out.println("How much would you like to deposit?");
input1= keyboard.nextDouble();
savAcct.deposit(input1);
System.out.println("Your balance is " + savAcct.getBalance() );
}
if (accountActivity.equalsIgnoreCase("withdraw"))
System.out.println("How much would you like to withdraw?");
input1= keyboard.nextDouble();
savAcct.withdraw(input1);
System.out.println("Your balance is "+ savAcct.getBalance());
}
}while (!accountChoice.equalsIgnoreCase("Q"));
}
}

You're missing a set of curly braces after this statement:
if(accountChoice.equalsIgnoreCase("regular"))
...and this statement:
if (accountActivity.equalsIgnoreCase("withdraw"))
The default behavior for Java (and C, and C++) is to execute only the next line after an if, for, or while statement if curly braces are omitted.
When you're done, your statement should look like this:
if(accountChoice.equalsIgnoreCase("regular")) {
System.out.println("What action do you wish to perform(deposit, withdraw or monthly process)? ");
accountActivity = keyboard.nextLine();
// Rest of code that concerns activity with a "regular" account
}

You have to make sure you read both options at the start; accountChoice and accountActivity. One issue with your code is the lack of { and } usage.
So it would be like...
do { // do below first before checking the while condition
if(accountChoice.equalsIgnoreCase("regular"))
{
// do your work.
} else if (accountChoice.equalsIgnoreCase("savings"))
{
// do the rest
}
} while (!accountChoice.equalsIgnoreCase("Q"));
Below is the modified code.
public class Crawford_Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double input1;
String accountChoice;
String accountActivity;
RegularAccount regAcct = new RegularAccount(0, .5);
SavingsAccount savAcct = new SavingsAccount(0, .5);
do {
System.out.println("What account would you like to access(regular or savings)?" );
accountChoice = keyboard.nextLine();
System.out.println("What action do you wish to perform(deposit, withdraw or monthly process)? ");
accountActivity = keyboard.nextLine();
if(accountChoice.equalsIgnoreCase("regular")) { // LINE moved and BRACKET MISSING
if (accountActivity.equalsIgnoreCase("deposit"))
{
System.out.println("How much would you like to deposit?");
input1= keyboard.nextDouble();
regAcct.deposit(input1);
System.out.println("Your balance is " + regAcct.getBalance() );
}
else if (accountActivity.equalsIgnoreCase("withdraw"))
{
System.out.println("How much would you like to withdraw?");
input1= keyboard.nextDouble();
regAcct.withdraw(input1);
System.out.println("Your balance is "+ regAcct.getBalance());
}
else if (accountActivity.equalsIgnoreCase("monthly process"))
{
regAcct.monthlyProcess();
}
}
else if (accountChoice.equalsIgnoreCase("savings"))
{ // line changed & BRACKET MISSING
if (accountActivity.equalsIgnoreCase("deposit"))
{
System.out.println("How much would you like to deposit?");
input1= keyboard.nextDouble();
savAcct.deposit(input1);
System.out.println("Your balance is " + savAcct.getBalance() );
}
else if (accountActivity.equalsIgnoreCase("withdraw"))
{ // bracket missing
System.out.println("How much would you like to withdraw?");
input1= keyboard.nextDouble();
savAcct.withdraw(input1);
System.out.println("Your balance is "+ savAcct.getBalance());
}
}
} while (!accountChoice.equalsIgnoreCase("Q"));
}
}

Related

Using main how do I pass a user entered value to its destination class

My assignment was to create the front end of an imaginary bank. The system asks the user for balance, and if they'd like to deposit or withdraw. In a separate class BankAccount.java I have declared public static double balance;. This is the value that holds the users' balance after they have entered it. This all works perfectly except for bankAccount.balance = scanner.nextDouble();. When the user enters their balance the program ends.
This is what the terminal outputs:
What is your current account balance :
10
Would you like to withdraw or deposit money through your account?
Process finished with exit code 0
For clarification, the opportunity to enter "withdraw" or "deposit" isn't actualized, the question is output as fast as the program ends.
I've marked the line causing me grief with //<-- PROBLEM LINE
public class Bank
{
public static void main(String[] args)
{
//System.out.println( "" );
Scanner scanner = new Scanner( System.in );
BankAccount bankAccount = new BankAccount();
System.out.println( "What is your current account balance :" );
bankAccount.balance = scanner.nextDouble(); //<-- PROBLEM LINE
System.out.println("Would you like to withdraw or deposit money through your account?");
String choice = scanner.nextLine();
if ( choice.equals( "deposit" ) )
{
System.out.println("How much money would you like to deposit?");
bankAccount.deposit(scanner.nextDouble());
}
if ( choice.equals( "withdraw" ) )
{
System.out.println( "How much money would you like to withdraw?" );
try
{
System.out.println( "Your new account balance is : $" + bankAccount.withdraw(scanner.nextDouble()) );
}
catch ( NotEnoughBalanceException e )
{
e.printStackTrace();
}
}
}
}
Just use the scanner.nextLine() and if you need a double just parse it.
public static void main(String[] args) {
//System.out.println( "" );
Scanner scanner = new Scanner(System.in);
BankAccount bankAccount = new BankAccount();
System.out.println("What is your current account balance :");
bankAccount.balance = Double.parseDouble(scanner.nextLine()); //<-- PROBLEM LINE
System.out.println("Would you like to withdraw or deposit money through your account?");
String choice = scanner.nextLine();
if (choice.equals("deposit")) {
System.out.println("How much money would you like to deposit?");
bankAccount.deposit(Double.parseDouble(scanner.nextLine()));
}
if (choice.equals("withdraw")) {
System.out.println("How much money would you like to withdraw?");
try {
System.out.println("Your new account balance is : $" + bankAccount.withdraw(Double.parseDouble(scanner.nextLine())));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I believe the problem is nextDouble() doesn't actually consume the newline from you pressing enter, so scanner.nextLine() returns immediately, returning an empty line. You could use nextLine() instead of nextDouble() and use the Double class to parse the result, like so:
bankAccount.balance = Double.parseDouble(scanner.nextLine());

How can I use input from user that exist inside of if statement in Java?

So what I trying to do is ask users to put their weight and score of exam 1 & 2 and if they input the score, use those variables to figure out current score.
However, since scores are declared by users through scanner inside of if statement, it does not let me use those variables from outside of if statement.
How can I use variable 'examOneScore' and 'examTwoScore' when I want to calculate csEx1 and csEx2.
When I try to use those it says "The local variable examOneScore may not have been initialized."
import java.util.Scanner;
public class CurrentScore
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("Weight of Exam 1: ");
double weightExamOne = keyboard.nextDouble();
System.out.printf("Weight of Exam 2: ");
double weightExamTwo = keyboard.nextDouble();
System.out.printf("Do you know your score of first exam? ");
String examOne = keyboard.nextLine();
if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
double examOneScore = keyboard.nextDouble();
}
System.out.printf("Do you know your score of secondexam? ");
String examTwo = keyboard.nextLine();
if(answerTwo.equalsIgnoreCase("yes") || answerTwo.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
double examTwoScore = keyboard.nextDouble();
}
double csEx1 = (weightExamOne * examOneScore);
double csEx2 = (weightExamTwo * examTwoScore );
}
}
You have to define the variables that you want to use later outside of the if statement:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("Weight of Exam 1: ");
double weightExamOne = keyboard.nextDouble();
System.out.printf("Weight of Exam 2: ");
double weightExamTwo = keyboard.nextDouble();
System.out.printf("Do you know your score of first exam? ");
String examOne = keyboard.nextLine();
double examOneScore = 1;
if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
examOneScore = keyboard.nextDouble();
}
System.out.printf("Do you know your score of second exam? ");
String examTwo = keyboard.nextLine();
double examTwoScore = 1;
if(examTwo.equalsIgnoreCase("yes") || examTwo.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
examTwoScore = keyboard.nextDouble();
}
double csEx1 = (weightExamOne * examOneScore);
double csEx2 = (weightExamTwo * examTwoScore );
}
I used the value 1 for defining them, you have to look for yourself want you want to use there

How do you call a method with parameters from main method if statement?

I am trying to call the method gasCost from the main method. I give the user the choice of entering a number to bring up a certain calculation, in this instance the user has selected option 3. The integer gallons_Gas is defined in the main method, so I am passing that into gasCost method.
I get an error after the else statement and can't compile. Says .class expected where the variable name gallons_Gas starts and after gallons_Gas says ; expected. What am I doing wrong and how do I fix this?
public class Deryck_HW2_TripCalculatorMenu
{
public static void main(String[] args)
{
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask for gallons of gas consumed
System.out.print("Gallons of Gas Consumed: ");
//Save gallons of gas consumed
int gallons_Gas = userInput.nextInt();
//Give user options menu
menu();
//Ask user choice
System.out.print("Choose from options above (enter number 1-4): ");
//Get user choice 1-4
int choice = userInput.nextInt();
//Test choice
if (choice == 1)
{
//avgSpeed();
}
else if (choice == 2)
{
//mpg();
}
else if (choice == 3)
{
gasCost(int gallons_Gas);
}
else
{
System.out.print("Error: selection invalid. Restart program and enter a number between 1 and 4.");
}
}
public static void gasCost(int gallons_Gas)
{
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask cost of gallon of gas
System.out.print("What is the cost per gallon of gas? ");
//Save cost per gallon
double gallon_Cost = userInput.nextDouble();
//Calculate total cost
double total_cost = (gallons_Gas * gallon_Cost);
System.out.print("Total cost of gas for this trip was $" + total_cost);
}
Try to understand what these lines mean and note how to call methods, how to pass in variables, when to declare variables etc...
import java.util.Scanner;
public class GasCalculator {
public static void main(String[] args) {
final int GALLONS_GAS = 100; // change this to whatever. It's good practice to use constants for variables that does not need to be immuted.
Scanner sc = new Scanner(System.in);
int user_choice = -1;
try {
user_choice = sc.nextInt();
} catch (Exception e) {
System.out.println("Only enter integers.");
main(args);
return;
}
switch(user_choice) {
case 1:
// do something.
break;
case 2:
// do something.
break;
case 3:
gasCost(GALLONS_GAS);
break;
default:
System.out.println("Bad input");
main(args);
break;
}
sc.close();
}
public static void gasCost(int gallons_Gas) {
//Get a scanner instance
Scanner userInput = new Scanner(System.in);
//Ask cost of gallon of gas
System.out.print("What is the cost per gallon of gas? ");
//Save cost per gallon
// should try using a try-catch here to handle InputMismatchException
double gallon_Cost = userInput.nextDouble();
//Calculate total cost
double total_cost = (gallons_Gas * gallon_Cost);
System.out.print("Total cost of gas for this trip was $" + total_cost);
userInput.close();
return;
}
}
I don't know if this is a pseudo-code or just the real code. If it is the real code, there are several mistakes:
gasCost(int gallons_Gas);
You should know the differences between formal parameters and actual parameters. In the actual parameters type of variable is not required, instead of formal parameters. Link:
What is a formal parameter in Java?
So, that code should be like:
int gallons_gas = 5; //Just for example
gasCost(gallons_Gas);
After that, you should listen to the guys in the comments: be sure where that else if statement is, if you put it in the wrong way it won't work.
Hope it helps
gasCost(int gallons_Gas);
should be
int gallons_Gas;
if (...) {
gasCost(gallons_Gas);
}
You cannot declare an int within the parameter list of a method call.

Why does it skip the "control" segment? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
so I'm trying to ask the user to input value for control right after the SOP is done. But it skips it for some reason.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What's your balance?");
double initialBalance = keyboard.nextDouble();
Account chase = new Account(initialBalance);
System.out.println(chase + "; Would you like to deposit or withdraw?");
String control = keyboard.nextLine();
if(control == "deposit")
{
double deposit = keyboard.nextDouble();
System.out.println("How much would you like to deposit? " +
deposit);
chase.deposit(deposit);
System.out.println(chase);
}
}
Here is a snippet of your code with the changes required.
Scanner keyboard = new Scanner(System.in);
System.out.println("What's your balance?");
double initialBalance = keyboard.nextDouble();
keyboard.nextLine();
Account chase = new Account(initialBalance);
System.out.println("; Would you like to deposit or withdraw?");
String control = keyboard.nextLine();
if (control .equals("deposit") ){
System.out.println("How much would you like to deposit? " );
double deposit = keyboard.nextDouble();
keyboard.nextLine();
The comments are clear. You would need to see the two post that they pointed to. Briefly there is a line separator that comes in and the importance of the equals method and its significance.
New Code:
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What's your balance?");
double initialBalance = keyboard.nextDouble();
Account chase = new Account(initialBalance);
System.out.println(chase + "; Would you like to deposit or withdraw?");
String control2 = "deposit";
boolean control = keyboard.next().equalsIgnoreCase(control2);
if(control == true)
{
double deposit = keyboard.nextDouble();
System.out.println("How much would you like to deposit? " +
deposit);
chase.deposit(deposit);
System.out.println(chase);
}
}
}

How can I write an "if" statement for a string variable in Java?

This is what I have so far and I have the problem written as a comment on the line I need help with. Any further suggestions would be welcome too. I just need it to end the program when the user enters "stop" as the employee name. Thanks in advance.
package payroll_program_2;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
float hours;
float rate;
String name;
float total_pay;
System.out.println("Please enter employee name");
name = input.next();
if (stop) //THIS IS WHAT I NEED HELP WITH. I DO NOT KNOW HOW TO WRITE
end program //IT CORRECTLY, SO I JUST TYPED WHAT I NEED IT TO DO.
{
}
System.out.println("Please enter hourly rate");
rate = input.nextFloat();
if (rate <0)
{
System.out.printf("Pay rate cannot be negative");
}
System.out.println("Please enter hours worked");
hours = input.nextFloat();
if (hours <0)
{
System.out.printf("Hours cannot be negative");
}
System.out.println("Employee's total pay for this week");
total_pay = hours*rate;
System.out.printf("The total pay for %s is $%.2f\n", name, total_pay);
}
if (name.equals("stop")) {
return;
}

Categories