Failed Logic in project - java

The purpose of the project is to gather user input and output certain prices based on your input. When entering data, it seems as if none of my logic is working and it is returning 0 for a value.
PS. The problem that is wrong is the total price of the cell phone plan. When i call my methods from the main method everything runs but I am assuming my equations aren't correct.
import java.util.Scanner; // gathers user input
public class Exam2Hassan {
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
int numOfPhones = 0, choice = 0;
double finalCost = 0, basePrice = 0, cellPlanCost = 0;
char goAgain;
// holds menu selection
final int MENU_OPTION_ONE = 1;
final int MENU_OPTION_TWO = 2;
final int MENU_OPTION_THREE = 3;
final int MENU_OPTION_FOUR = 4;
// calls all methods
displayData();
basePrice = basePricing(choice);
cellPlanCost = calculateCost(numOfPhones, basePrice);
finalCost = displayFinalCost(cellPlanCost);
} // end main
/**
This method displays the data plan menu, should not accept any arguments or return any value
*/
public static void displayData() {
Scanner keyboard = new Scanner(System.in); // allows user input
int choice, numOfPhones;
double cellPlanCost = 0;
double totalCost = 0;
char goAgain;
System.out.print("Data Plan Menu: ");
System.out.println();
System.out.println();
System.out.println("\t1. 1 GB");
System.out.println("\t2. 2 GB");
System.out.println("\t3. 3 GB");
System.out.println("\t4. 4 GB");
System.out.println();
do { // allows user to input how many plans they want to process
System.out.print("Select a plan from the menu above: ");
choice = keyboard.nextInt();
while(choice < 1 || choice > 4)//validate the user's input
{
System.out.print("Selection must be between 1 and 4. Select a plan from the menu above: ");
choice = keyboard.nextInt();
}
System.out.print("Enter the number of phones: ");
numOfPhones = keyboard.nextInt();
while(numOfPhones < 1) //validate the user's input
{
System.out.print("Number of phones must be at least 1. Enter the Number of phones: ");
numOfPhones = keyboard.nextInt();
}
System.out.printf("The total price of the cell phone plan (before tax and fees) is: $%.2f\n", totalCost);
System.out.println();
keyboard.nextLine();
System.out.println();
System.out.print("Do you wish to calculate the price of another plan (Y/N)? ");
goAgain = keyboard.nextLine().charAt(0);
System.out.println();
}
while(goAgain == 'Y' || goAgain == 'y');
}
/**
This method accepts the menu selection as an argument and shows which data plan was selected. should return base pricing
*/
public static double basePricing(int choice){
final double ONE_GB = 34.99;
final double TWO_GB = 49.99;
final double FOUR_GB = 64.99;
final double UNLIMITED_GB = 74.99;
double basePrice = 0;
if(choice == 1) {
basePrice = 34.99;
}
else if(choice == 2) {
basePrice = 49.99;
}
else if(choice == 3) {
basePrice = 64.99;
}
else if(choice == 4) {
basePrice = 74.99;
}
return basePrice;
}
/**
This method calculates the cost of a cell plan. Accepts number of lines and base pricing. returns the cost of the plan
*/
public static double calculateCost(int numOfPhones, double basePrice) {
double cellPlanCost = 0;
cellPlanCost = basePrice + (10.00 * numOfPhones);
return cellPlanCost;
}
/**
This method should display the final cost. accepts the final cost as argument
*/
public static double displayFinalCost(double cellPlanCost) {
return cellPlanCost;
}
} // end class

Immediately after entering the number of phones , there are no logic to calculate cost before printing.
I would suggest you to call following methods after entering number of phones inside the displayData() method and use finalCost or appropriate variable based on your requirement.
basePrice = basePricing(choice);
cellPlanCost = calculateCost(numOfPhones, basePrice);
finalCost = displayFinalCost(cellPlanCost);

Below is the code for the same.
import java.util.Scanner; // gathers user input
public class Exam2Hassan {
public static void main(String [] args) {
// calls all methods
displayData();
} // end main
/**
This method displays the data plan menu, should not accept any arguments or return
any value
*/
public static void displayData() {
Scanner keyboard = new Scanner(System.in); // allows user input
int choice, numOfPhones;
double cellPlanCost = 0;
double basePrice=0;
char goAgain;
System.out.print("Data Plan Menu: ");
System.out.println();
System.out.println();
System.out.println("\t1. 1 GB");
System.out.println("\t2. 2 GB");
System.out.println("\t3. 3 GB");
System.out.println("\t4. 4 GB");
System.out.println();
do { // allows user to input how many plans they want to process
System.out.print("Select a plan from the menu above: ");
choice = keyboard.nextInt();
while(choice < 1 || choice > 4)//validate the user's input
{
System.out.print("Selection must be between 1 and 4. Select a plan from the menu above: ");
choice = keyboard.nextInt();
}
basePrice=basePricing(choice);
System.out.print("Enter the number of phones: ");
numOfPhones = keyboard.nextInt();
while(numOfPhones < 1) //validate the user's input
{
System.out.print("Number of phones must be at least 1. Enter the Number of phones: ");
numOfPhones = keyboard.nextInt();
}
cellPlanCost = calculateCost(numOfPhones, basePrice);
System.out.printf("The total price of the cell phone plan (before tax and fees) is: $%.2f\n", cellPlanCost);
System.out.println();
keyboard.nextLine();
System.out.println();
System.out.print("Do you wish to calculate the price of another plan (Y/N)? ");
goAgain = keyboard.nextLine().charAt(0);
System.out.println();
}
while(goAgain == 'Y' || goAgain == 'y');
}
/**
This method accepts the menu selection as an argument and shows which data plan was
selected. should return base pricing
*/
public static double basePricing(int choice){
double basePrice = 0;
if(choice == 1) {
basePrice = 34.99;
}
else if(choice == 2) {
basePrice = 49.99;
}
else if(choice == 3) {
basePrice = 64.99;
}
else if(choice == 4) {
basePrice = 74.99;
}
return basePrice;
}
/**
This method calculates the cost of a cell plan. Accepts number of lines and base
pricing. returns the cost of the plan
*/
public static double calculateCost(int numOfPhones, double basePrice) {
double cellPlanCost = 0;
cellPlanCost = basePrice + (10.00 * numOfPhones);
return cellPlanCost;
}
/**
This method should display the final cost. accepts the final cost as argument
*/
public static double displayFinalCost(double cellPlanCost) {
return cellPlanCost;
}
} // end class

Related

Calling a method to try and rerun through a block of code

I'm trying to compare the cost of a user's phone usage under plans from three
different providers. I can get as far as entering the usage details but once entered I try to call the method to rerun from the if statement but it just displays the main menu again and stops. I want it to run through the entire if statement from the start again
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel ;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel >4){
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection >6){
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
System.out.println("Hello World!");
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
} else {
mainMenuSelection(); // go back to main menu
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
}
mainMenuSelection = mainMenuSelection();
}
}
Codes run from top to bottom. Therefore, after the int mainMenuSelection = mainMenuSelection(); and the if-else statement is run, the code would run once again for the mainMenuSelection = mainMenuSelection() and ends, as there is nothing left in the block.
A fairly simple solution would be using a while or do-while loop with a boolean checking if the user entered the number 6 to exit the system.
You can try this example:
public static void main(String[] args) {
/*
* Your variables here
*/
boolean isExit = false;
while(!isExit) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
// menuSel codes here
} else if (mainMenuSelection == 2) {
// Display cost under provider 1
} else if (mainMenuSelection == 3) {
// Display cost under provider 2
} else if (mainMenuSelection == 4) {
// Display cost under provider 3
} else if (mainMenuSelection == 5) {
// Clear usage details
} else {
System.out.println("Exiting System");
isExit = true;
}
}
Hopes this answer helps you well.
It looks like you need a loop. Your main method has an exit condition so you can essentially loop forever by wrapping the code in your main method with a while loop:
public static void main(String[] args) {
while(true) {
// your main method code in here
}
}
By the way, you need to edit your code above in good formatting.
I have added a while loop in your main. Also, whenever any unwanted number the loop will exit using a break; and that in turn stops the program.
mainMenuSelection = mainMenuSelection();
I have deleted the above line from the code so you just need to call it once at the beginning of the code.
Let me know if you need sth else!
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel > 4) {
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection > 6) {
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
while (true) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
break;
}
}
}
}

How to return Scanner.in value from the method to another method

I want to make some simple program which will count monthly rate of product. There is two inputs: cost of the product - between 100-10000 and number of rates - between 6-48. I wanted to do it like in the code below:
import java.util.Scanner;
public class Calculator {
Scanner sc = new Scanner (System.in);
double productCost;
int numberOfRates;
double loanInterestRate;
double monthlyRate;
Double print () {
Calculator c = new Calculator();
System.out.println ("Enter the value of your product from 100 to 10 000 : ");
productCost=sc.nextDouble();
if (productCost < 100){
System.out.println ("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >10000){
System.out.println ("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >= 100 || productCost <=10000){
c.print1();
return = productCost;
// how to return productCost to be used in next method print1()?
}
else return null;
}
void print1(){
Calculator c = new Calculator();
System.out.println ("Now enter how many rates do you want to pay from 6 to 48: ");
numberOfRates=sc.nextInt();
if (numberOfRates<6){
System.out.println ("You can't choose this number of rates. Choose between 6-48: ");
c.print1();
} else if (numberOfRates>48){
System.out.println ("You can't choose this number of rates. Choose between 6-48: ");
c.print1();
} else if (numberOfRates>=6 || numberOfRates<=12) {
loanInterestRate=1.025;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
} else if (numberOfRates>=13 || numberOfRates <=24 ) {
loanInterestRate=1.05;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
} else if (numberOfRates >=25|| numberOfRates<=48){
loanInterestRate=1.1;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
}
}
}
And the main method only calling the method from the other class.
public class MonthlyRate {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.print();
// TODO code application logic here
}
}
And what is the problem, I don't know how to return the "double productCost" from the method "print()". productCost is taking from the input and this is double but NetBeans showing me that it's not correct type. Can anybody help me understand where is the problem?
Simply do
return productCost;
return is a keyword, not a variable. It 'returns' the given value and exits the function, so that the entity calling the function can do this:
public static void main(String[] args) {
...
double cost = calc.print(); // note calc.print() PRODUCES a value, which we assign to `cost`
...
}
You can then do whatever you want with cost (or whatever you choose to name the variable), including passing it to another function.
Your program needs changes in a few places. I have done those changes and written below the updated program:
import java.util.Scanner;
class Calculator {
Scanner sc = new Scanner(System.in);
double productCost;
int numberOfRates;
double loanInterestRate;
double monthlyRate;
void print() {
Calculator c = new Calculator();
System.out.println("Enter the value of your product from 100 to 10 000 : ");
productCost = sc.nextDouble();
if (productCost < 100) {
System.out.println("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost > 10000) {
System.out.println("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >= 100 || productCost <= 10000) {
print1(productCost);
}
}
void print1(double productCost) {
Calculator c = new Calculator();
System.out.println("Now enter how many rates do you want to pay from 6 to 48: ");
numberOfRates = sc.nextInt();
if (numberOfRates < 6) {
System.out.println("You can't choose this number of rates. Choose between 6-48: ");
c.print1(productCost);
} else if (numberOfRates > 48) {
System.out.println("You can't choose this number of rates. Choose between 6-48: ");
c.print1(productCost);
} else if (numberOfRates >= 6 || numberOfRates <= 12) {
loanInterestRate = 1.025;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
} else if (numberOfRates >= 13 || numberOfRates <= 24) {
loanInterestRate = 1.05;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
} else if (numberOfRates >= 25 || numberOfRates <= 48) {
loanInterestRate = 1.1;
monthlyRate = (productCost * loanInterestRate) / numberOfRates;
System.out.printf("Your monthly rate is: " + "%.2f%n", monthlyRate);
}
}
}
public class MonthlyRate {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.print();
// TODO code application logic here
}
}
It is easy to understand the changes after comparing your program with this updated program. Nevertheless, feel free to let me know if you need any further help on this.

java - withdraw from bank account using a method

Building a basic bank account with Java using methods. I am creating a new method to withdraw from the bank account. This is the code that I came up with right now, but on netbeans it shows that there are errors.
I created a new method called withDrawal. This code below is for the withdrawing from account and to not let the balance in the account go below zero!
private static void withDrawal()
{
int accountIndex = findAccount();
int verifyPin = checkPin (!=0);
if(accountIndex != -1)
if(verifyPin !=-2)
{
accounts[accountIndex].withDrawal();
accounts[verifyPin].checkPin();
int withDra = input.nextInt();
}
else
{
System.out.println("Account does not exist!");
System.out.printf("Enter amount you want to withdraw: ");
}
}
Java file
package grossmontbank;
import java.util.Scanner;
public class GrossmontBank
{
//class variables (global - accessible throughout this class)
//scanner object to be used throughout
private static Scanner input = new Scanner(System.in);
//array of blank accounts
private static final int MAX_ACCOUNTS = 50;
private static Account[] accounts = new Account[MAX_ACCOUNTS];
//total accounts created
private static int totalAccounts = 0;
//main class mimics a bank teller
public static void main(String[] args)
{
char choice;
//loop until 'Q' is entered
do
{
choice = getChoice(); //getChoice() will only return with a C, B, W, D or Q
if(choice != 'Q')
{
switch(choice)
{
case 'C': createAccount();
break;
case 'B': checkBalance();
break;
case 'W':
break;
case 'D':
break;
}
}
}while(choice != 'Q');
closeBank(); //outputs all account holders and 'closes' the bank
}
/*method checkBalance calls method findAccount()
* if account exists, calls Account method checkBalance()
*/
private static void checkBalance()
{
int accountIndex = findAccount();
//findAccount() returns index of account if found, -1 if not found
if(accountIndex != -1)
{
accounts[accountIndex].checkBalance();
}
else
{
System.out.println("Account does not exist");
}
}
/*method checkIfExists determines if account holder already exists
* returns true if account holder exists, false otherwise
*/
private static boolean checkIfExists(String firstName, String lastName)
{
//loops through account array to see if account name already exists
for(int i = 0; i < totalAccounts;i++)
{
//compares the names, ignoring upper/lower
if(accounts[i].getFirstName().equalsIgnoreCase(firstName)
&& accounts[i].getLastName().equalsIgnoreCase(lastName))
{
System.out.println("Account holder already exists. Please verify and re-enter. ");
return true;
}
}
return false;
}
/*method closeBank prints out closing statement
* prints out list of all account holders
*/
private static void closeBank()
{
System.out.println("Closing the follow accounts:");
for(int i = 0; i < totalAccounts;i++)
{
//printing an account object invokes the Account class method toString()
//prints first and last name only
System.out.printf(" %s%n",accounts[i]);
}
System.out.println("Grossmont Bank is officially closed.");
}
/*method createAccount creates a single bank account
* checks to ensure account holder does not already exist
* returns Account object
*/
private static void createAccount()
{
String first, last, initial;
boolean exists = false;
//only create a new account if MAX_ACCOUNTS has not been reached
if(totalAccounts < MAX_ACCOUNTS )
{
//loop until a new account name has been entered
do
{
System.out.print("Enter your first name: ");
first = input.next();
System.out.print("Enter your last name: ");
last = input.next();
exists = checkIfExists(first,last);
}while(exists == true);
System.out.print("Will you be making an initial deposit? Enter Yes or No: ");
initial = input.next();
//if no initial deposit, call 2 parameter constructor, otherwise call 3 param one
if(initial.equals("No"))
{
accounts[totalAccounts] = new Account(first,last);
}
else
{
System.out.print("Enter initial deposit amount: ");
accounts[totalAccounts] = new Account(first,last, input.nextDouble());
}
//increment totalAccounts created (used throughout program)
totalAccounts++;
}
else
{
System.out.println("Maximum number of accounts has been reached. ");
}
}
/*method findAccount asks for first and last name
* searchs for account holder in array
* if exists, returns array index of this account
* if doesn't exist, returns '-1'
* called from checkBalance()
*/
private static int findAccount()
{
String first, last;
System.out.print("Enter first name: ");
first = input.next();
System.out.print("Enter last name: ");
last = input.next();
//loops through account array
for(int i = 0; i < totalAccounts;i++)
{
//compares the names, ignoring upper/lower
if(accounts[i].getFirstName().equalsIgnoreCase(first)
&& accounts[i].getLastName().equalsIgnoreCase(last))
{
return i; //returns the index of the account
}
}
return -1; //if account not found
}
/* method getChoice() outputs options
* inputs choice from user and validates
* returns choice char
*/
private static char getChoice()
{
char choice;
//output menu options
System.out.println();
System.out.println("Welcome to Grossmont Bank. Choose from the following options: ");
System.out.println(" C - create new account");
System.out.println(" B - check your balance");
System.out.println(" D - deposit");
System.out.println(" W - withdrawal");
System.out.println(" Q - quit");
//loop until a valid input is entered
do
{
System.out.print("Enter choice: ");
choice = input.next().charAt(0);
//if choice is one of the options, return it. Otherwise keep looping
if(choice == 'C' || choice == 'B' || choice == 'D' || choice == 'W' || choice == 'Q')
return choice;
else
{
System.out.println("Invalid choice. Ensure a capital letter. Please re-enter.");
choice = '?';
}
}while(choice == '?');
return choice; //will never get here, but required to have a return statement to compile
}
private static void withDrawal()
{
int accountIndex = findAccount();
int verifyPin = checkPin (!=0);
if(accountIndex != -1)
if(verifyPin !=-2)
{
accounts[accountIndex].withDrawal();
accounts[verifyPin].checkPin();
int withDra = input.nextInt();
}
else
{
System.out.println("Account does not exist!");
System.out.printf("Enter amount you want to withdraw: ");
}
}
}

I keep getting multiple errors each time I try to compile the program. Not sure where I went wrong

import java.util.Scanner;
public class CoffeeShop {
public static void main(String[] args) {
//Welcome message
String username;
System.out.println("Please enter your name");
Scanner keyboard = new Scanner(System.in);
username = keyboard.next();
System.out.println("Welcome to the Java Byte Code Coffee Shop," + username + "!");
//Menu
System.out.println("Here is our menu.");
System.out.println("1. Coffee $1.50");
System.out.println("2. Latte $3.50");
System.out.println("3. Cappuccino $3.25");
System.out.println("4. Expresso $2.00");
//Item selection
int item_Number;
System.out.println("Please enter an item number.");
Scanner item = new Scanner(System.in);
item_Number = item.nextInt();
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
//Item Quantity
int quantity;
System.out.println("Please enter the quantity.");
Scanner amount = new Scanner(System.in);
quantity = amount.nextInt();
double total = quantity * item;
System.out.println("Total before discount and tax is " + total);
//Discount and tax
double nuTotal;
if(total >= 10) {
nuTotal = total - (total * .1);
} else {
nuTotal = total;
}
System.out.println("Your total with discount is " + nuTotal);
double totalTax = nuTotal * .07;
System.out.println("Your total with tax is " + totalTax);
System.out.println("Thank you " + username + "! Please stop by again!");
}
}
Your assignment is to write a program called CoffeeShop (in the file CoffeeShop.java) that simulates a virtual coffee shop, allowing the user to select an item to purchase, along with the quantity of that item. After obtaining the item selection and desired quantity from the user, your program should calculate the cost, tax, discount, and final cost, then display these to the user.
The problem starts here:
Scanner item = new Scanner(System.in);
item_Number = item.nextInt();
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
item is a Scanner object but then you attempt to assign it a double value.
Then double total = quantity * item;. You multiply by a Scanner object.
Your error is in the following code.
First you declare:
Scanner item = new Scanner(System.in);
Then you try to set that scanner variable to be what I presume to be the price.
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
In order to fix this what you should do is set these numbers to a new variable, such as:
double price = 0;
price = ...; //not: item = ...;
Then you can calculate your total simply by:
double total = quantity * price;
Hope this helps! Just try to be very careful when setting variables :)
I believe your code should be similar to:
double price = 0;
if(item_Number == 1) {
price = 1.50;
}
if(item_Number == 2) {
price = 3.50;
}
if(item_Number == 3) {
price = 3.25;
}
if(item_Number == 4) {
price = 2.00;
}
double total = quantity * price;
This should help you a bit!
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
//Welcome message
String username;
double item = 0.0;
Scanner keyboard = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Please enter your name");
username = keyboard.next();
System.out.println("Welcome to the Java Byte Code Coffee Shop," + username + "!");
//Menu
System.out.println("Here is our menu.");
System.out.println("1. Coffee $1.50");
System.out.println("2. Latte $3.50");
System.out.println("3. Cappuccino $3.25");
System.out.println("4. Expresso $2.00");
//Item selection
int item_Number = 0;
System.out.println("Please enter an item number.");
item_Number = keyboard.nextInt();
if (item_Number == 1) {
item = 1.50;
}
if (item_Number == 2) {
item = 3.50;
}
if (item_Number == 3) {
item = 3.25;
}
if (item_Number == 4) {
item = 2.00;
}
//Item Quantity
int quantity = 0;
System.out.println("Please enter the quantity.");
quantity = keyboard.nextInt();
double total = quantity * item;
System.out.println("Total before discount and tax is $ " + df.format(total));
//Discount and tax
double nuTotal;
if (total >= 10) {
nuTotal = total - (total * 0.10);
} else {
nuTotal = total;
}
System.out.println("Your total with discount is $" + df.format(nuTotal));
double totalTax = nuTotal + (nuTotal * 0.07);
System.out.println("Your total with tax is: $" + df.format(totalTax));
System.out.println("Thank you " + username + "! Please stop by again!");
}
}
I advise you to follow name patterns for the Java programming language and its variables... you could see the documentation in here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
I also suggest you to initialize your variables in order to avoid Null values while validating.
Hope this helps! It's working already... but I'm not sure what are your expectations, good luck!

How to keep requesting user to select a valid option?

So, the user has to choose a number between 1 and 3. Otherwise, they're told to try again. If the user tries a number less than 1 or greater than 3, whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop. I assumed there would be an easy solution, but apparently it's beyond me as a beginner. The obvious thing to me would be to somehow clear or empty the value that has been assigned to "choice" after the unsuccessful user input. Is that possible?
import java.util.Scanner;
public class Furniture2Test {
public static void main(String[] args) {
wood();
} // end main
public static void wood() {
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = keyboard.nextInt();
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
} else if (choice > 3 || choice < 1) {
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice) {
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = keyboard.nextInt();
if (sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else if (sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
}
Your requirement can be done easily with do...while loop. Sample code is as follows:
do{
System.out.println("Choose option between 1 and 3");
choice = keyboard.nextInt();
}while(!(choice > 3 || choice < 1));
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
}
Hope this helps.
//put the menu logic
while(choice > 3 || choice < 1) {
//put your try again logic.
}
//can only exit the while loop if the number is 1, 2, or 3, so put your output statement down here after the while loop
import java.util.Scanner;
public class Furniture2Test
{
public static void main(String[] args)
{
wood();
} // end main
public static void wood()
{
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = read_range(keyboard, 1, 3);
if(choice == 1)
{
choice = pineCost;
}
else
if(choice == 2)
{
choice = oakCost;
}
else
if(choice == 3)
{
choice = mahoganyCost;
}
else
if(choice > 3 || choice < 1)
{
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice)
{
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = read_range(keyboard, 1, 2);
if(sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else
if(sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
private static int read_range (Scanner scanner, int low, int high) {
int value;
value = scanner.nextInt();
while (value < low || value > high) {
System.out.print("Please enter a value between " + low + " and " + high + ": ");
value = scanner.nextInt();
}
return value;
}
} // end class
whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop//
the program is contining to run because you are calling wood() if(choice > 3 || choice < 1)
if you want it to stop remove the wood() call
if you also want to clear the value for choice(instead of -1) you can assign it to null
choice is a local variable to the method wood, you are making a recursive call to wood when the user makes a wrong choice. This is an interesting design choice and probably not the best in this case.
When you call wood again, choice is rest (in this to unknown value until it is assigned value from the user).
Now the problem occurs when the wood method exists...each time it returns to the caller, it will call size(choice), where choice is -1 (because that's what you set it to before calling wood again).
You should be using a while-loop instead of recursive calls
You should never call size(choice) with anything other then a valid choice
Take a look at The while and do-while statement for more details

Categories

Resources