public static void main(String[] args) {
Scanner keybNum = new Scanner(System.in);
Scanner keybStr = new Scanner(System.in);
boolean yn = false;
//Start of program
System.out.println("Welcome to Currency Exchanger");
System.out.print("Are you an Account Holder (y or n)? ");
String AccHolder = keybStr.next();
boolean blnYN = true;
//validation of y/n answer
while (blnYN) {
if (AccHolder.equalsIgnoreCase("y")) {
yn = true;
blnYN = false;
break;
}//if
else if (AccHolder.equalsIgnoreCase("n")) {
yn = false;
blnYN = false;
break;
}//else if
else {
System.out.println("Invalid value entered. Choose either y/n.");
AccHolder = keybStr.next();
}//else
}//while
//Start of menu choices
System.out.println("Please choose from the following menu.");
System.out.println("\n1: Exchange another currency for Sterling");
System.out.println("2: Buy another currency from us");
System.out.println("0: Exit");
System.out.print("Which option? ");
int MenuChoice = keybNum.nextInt();
//Exchange Variables (First option)
double Euro = 1.37;
double USAD = 1.81;
double JapYen = 190.00;
double Zloty = 5.88;
//Buy Variables (Second Option)
double EuroB = 1.21;
double USADB = 1.61;
double JapYenB = 163.00;
double ZlotyB = 4.89;
//First menu choice screen
if (MenuChoice == 1) {
System.out.println("Currencies to exchange into sterling?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
//Exchange amount calculator
System.out.print("Enter the amount you wish to exchange of " + CurChoice + ": ");
double ExcAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = ExcAmount / Euro;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("USD")) {
result = ExcAmount / USAD;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("JPY")) {
result = ExcAmount / JapYen;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("PLN")) {
result = ExcAmount / Zloty;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else {
System.out.println("");
}
Right, this is where I am stuck. So this program is a currency exchange converter. The part I'm unsure about is to calculate the commission. At the start I ask the user if they're an account holder. If they're they don't get charged a commission, whereas if they're then they do. If the amount they wish to exchange is less than £1000 then they get charged a commission of 2%, and if its over £1000 then they get charged a commission of 1%. I wasn't sure how to implement this into my program, so i'm asking you guys to help.
Try this after calculating the result:
double commission = 0.;
if (ExcAmount < 1000) {
commission = result * 0.02;
} else {
commission = result * 0.01;
}
result += commission;
String stringToPrint = "";
if (!yn) { //you could use meaningful variable names
stringToPrint = "Commission = " + commission;
} else {
stringToPrint = "Commission = Not charged";
}
System.out.println(stringToPrint + "\nTotal = " + (result - commission));
Related
My question is in relation to my line of code resembling an ATM. The current balance being 10000, What i have written shows a message to the user that if they withdraw over the given balance that it is Insufficient balance. However the balance continues to change thus when Inquiring balance the balance is now < the allowed balance. My question is how should i go about resetting the double value for the balance when the Insufficient balance message is shown to the user?
Here is my code.
import java.util.Scanner;
class app {
public static void main(String[] args)
{
long pin = 2927942074l;
double balance = 10000.0;
int attempts = 3;
System.out.println("Please enter your pin.");
while (attempts > 0) {
Scanner keyboardpin = new Scanner(System.in);
long input = keyboardpin.nextLong();
if (input == pin) {
System.out.println("Correct");
System.out.println("Welcome to your ATM");
while (true) { // Keep printing your options unless "Quit" is chosen
int a = 1;
int b = 2;
int c = 3;
int d = 0;
System.out.println(a + " - Inquire Balance");
System.out.println(b + " - Withdraw");
System.out.println(c + " - Deposit");
System.out.println(d + " - Quit");
System.out.println("Please select what you want to do.");
Scanner menuselect = new Scanner(System.in);
int menuinput = menuselect.nextInt();
if (menuinput == a) {
System.out.println(balance);
continue;
}
if (menuinput == b) {
System.out.println("Please enter a withdrawal amount.");
Scanner withdrawamount = new Scanner(System.in);
double withdrawbalace = withdrawamount.nextDouble();
balance = (balance - withdrawbalace);
if (withdrawbalace > balance)
System.out.println("Insufficient balance");
if (withdrawbalace <= balance)
System.out.println("Youre new balance is " + balance);
}
if (menuinput == c) {
}
if (menuinput == d) {
break;
}
if (attempts == 0) {
System.out.println("Maximum number of attempts exceeded");
}
}
} else {
System.out.println("Wrong");
attempts--;
System.out.println("You have " + attempts + " attempts remaining.");
}
}
}
}
Just check whether the user has enough balance before subtracting the amount.
if (menuinput == b) {
System.out.println("Please enter a withdrawal amount.");
Scanner withdrawamount = new Scanner(System.in);
double withdrawbalace = withdrawamount.nextDouble();
if (withdrawbalace > balance)
System.out.println("Insufficient balance");
if (withdrawbalace <= balance)
balance = (balance - withdrawbalace);
System.out.println("Youre new balance is " + balance);
}
Your main problem has been solved in the previous answer, but your code logic has some errors. I have fixed it for you.
import java.util.Scanner;
class app {
public static void main(String[] args) {
final long pin = 2927942074L;
double balance = 10000.0;
int attempts = 3;
System.out.println("Please enter your pin.");
Scanner keyboard = new Scanner(System.in);
while (attempts > 0) {
long input = keyboard.nextLong();
if (input == pin) {
System.out.println("Correct");
System.out.println("Welcome to your ATM");
// Keep printing your options unless "Quit" is chosen
while (true) {
int a = 1;
int b = 2;
int c = 3;
int d = 0;
System.out.println(a + " - Inquire Balance");
System.out.println(b + " - Withdraw");
System.out.println(c + " - Deposit");
System.out.println(d + " - Quit");
System.out.println("Please select what you want to do.");
int menuInput = keyboard.nextInt();
if (menuInput == a) {
System.out.println(balance);
} else if (menuInput == b) {
System.out.println("Please enter a withdrawal amount.");
double withdrawBalance = keyboard.nextDouble();
if (balance >= withdrawBalance) {
balance -= withdrawBalance;
System.out.println("Your new balance is " + balance);
} else System.out.println("Insufficient balance");
} else if (menuInput == c) {
// Deposit code here
} else if (menuInput == d) break;
}
} else {
attempts--;
if (attempts == 0) {
System.out.println("Maximum number of attempts exceeded");
break;
}
System.out.println("Wrong");
System.out.println("You have " + attempts + " attempts remaining.");
}
}
keyboard.close();
}
}
And here are some tips...
Try to choose meaningful variable names.
If the variable has a constant value make it final
If the variable name consists of two, or more, words capitalize the first letter of the second word (eg. menuInput)
If you check the same condition for different cases you can use switch or if, else if, else
Never forget to close the objects you used to release memory
Good Luck
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean start = true;
while(start)
System.out.printf("%70s %n", " ##### Zoos Australia ##### " + "\n");
System.out.printf("%57s %n", "Main Menu" + "\n");
System.out.printf("%72s %n", "Zoo has the following ticketing options:");
System.out.print("\n");
System.out.printf("%59s %n", "1 = Child (4-5 yrs)");
System.out.printf("%59s %n", "2 = Adult (18+ yrs)");
System.out.printf("%60s %n", "3 = Senior (60+ yrs)");
System.out.println("\n");
String choose1 = "";
String choose2 = "";
String choose3 = "";
String selected = "";
int option = 0;
{
System.out.print("Please select an option: ");
option = input.nextInt();
if (option == 1) {
choose1 = "Child";
selected = choose1;
} else if (option == 2) {
choose2 = "Adult";
selected = choose2;
} else if (option == 3) {
choose3 = "Senior";
selected = choose3;
}
}
// done
System.out.println("\n");
int price = 0;
int tickets = 0;
System.out.print("Enter the number of tickets: ");
tickets = input.nextInt();
if (selected == choose1) {
price = 10;
} else if (selected == choose2) {
price = 20;
} else if (selected == choose3) {
price = 15;
}
System.out.println("\n");
System.out.print("You are purchasing " + tickets + " " + selected + " tickets at " + "$" + price + " each!");
System.out.println("\n");
int confirm = 0;
System.out.print("Press 1 to confirm purchase: ");
confirm = input.nextInt();
if (confirm != 1) {
System.out.print("Incorrect Key. Please return to Main Menu");
System.out.println("\n");
} else {
break;
}
System.out.println("\n");
int total = tickets;
price = total * price;
System.out.print("Total amount for " + selected + " tickets: " + "$" + price);
System.out.println("\n");
String pick = "";
System.out.print("Do you wish to continue: ");
input.next();
System.out.println("\n");
if (pick == "no") {
System.out.print("Total amount payable is: " + "$" + price);
System.out.println("\n");
System.out.print("Have a nice day!");
System.out.println("\n");
}}}
Trying to do this at the end of the program where user is asked "Do you wish to continue" using a method or something but cant get it to work. Either the program returns to main menu only or the program ends and displays the total message "Total amount payable..." etc. I have tried using while with continue and break. Using boolean with true and false. But no luck. Thank you anyone that may be able to clear this up for me please.
First, you have to assign the users's input to a variable: pick = input.next(). After that, the problem is that you compare the user's input string with a "no" string by using == operator. When comparing reference types (objects) (and String is an object), in most cases == operator gives you an unpredictable result, because it compares the reference (address of an object in memory) and not the actual content. Please remember, that you always have to use the .equals() method instead. You also have to break from your loop, when the user's input is "no".
There is plenty of material concerning this issue. You can check, for instance, this one How do I compare strings in Java?
P.S. I quickly looked at the rest of your code and put some additional comments, which might help you to improve it. Good luck with learning Java!
Scanner input = new Scanner(System.in);
// boolean start = true; you don't need this line
while(true) { // 'true' condition makes it an infinite loop until you use break
// You also have to surround your while loop with curly braces,
// otherwise you fall into an infinite loop
System.out.printf("%70s %n", " ##### Zoos Australia ##### \n");
System.out.printf("%57s %n", "Main Menu\n");
System.out.printf("%72s %n", "Zoo has the following ticketing options: \n");
System.out.printf("%59s %n", "1 = Child (4-5 yrs)");
System.out.printf("%59s %n", "2 = Adult (18+ yrs)");
System.out.printf("%60s %n", "3 = Senior (60+ yrs)\n");
String choose1 = "";
String choose2 = "";
String choose3 = "";
String selected = "";
int option = 0;
System.out.print("Please select an option: ");
option = input.nextInt();
if (option == 1) {
choose1 = "Child";
selected = choose1;
} else if (option == 2) {
choose2 = "Adult";
selected = choose2;
} else if (option == 3) {
choose3 = "Senior";
selected = choose3;
}
System.out.println(); // "\n" is a redundant argument
int price = 0;
int tickets = 0;
System.out.print("Enter the number of tickets: ");
tickets = input.nextInt();
if (selected.equals(choose1)) { // you should never compare strings with == operator! Always use .equals() instead
price = 10;
} else if (selected.equals(choose2)) {
price = 20;
} else if (selected.equals(choose3)) {
price = 15;
}
System.out.println();
System.out.print("You are purchasing " + tickets + " " + selected + " tickets at " + "$" + price + " each!");
System.out.println();
int confirm = 0;
System.out.print("Press 1 to confirm purchase: ");
confirm = input.nextInt();
if (confirm != 1) {
System.out.print("Incorrect Key. Please return to Main Menu");
System.out.println("\n");
} else {
//break; you cannot use 'break' in the if statement! You have to figure out another way, how to handle an invalid input
}
System.out.println();
int total = tickets;
price = total * price;
System.out.print("Total amount for " + selected + " tickets: " + "$" + price);
System.out.println();
String pick = "";
System.out.print("Do you wish to continue: ");
pick = input.next(); // you have to assign the input to a variable
System.out.println();
if (pick.equals("no")) { // You have to ALWAYS use .equals() when comparing Strings or any other reference types! == works correctly only with primitive types
System.out.print("Total amount payable is: " + "$" + price);
System.out.println();
System.out.print("Have a nice day!");
System.out.println();
break; // you need to break from the loop in the end
}
}
}
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();
}
}
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();
}
}
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.