I just writed this program, it is to train myself for the upcomming exam this monday.
A thing i would like to add is: after a user is done with one of the exchange options 1/2/3 i would like to give the option to let the user return to the beginning welcome to the money exchange! etc.....
i have tried some a for loop and a while loop but i couldn't get it to work.
Would be cool if after the money exchange process that the user get the option to return to the beginning by typing y or n is this possible?
/* This program is written as a excercise to prep myself for exams.
* In this program the user can:
* 1. Select a currency (other than euro's)
* 2. Input the amount of money
* 3. transfer the amount of currency to euro's
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat() ;
df.setMaximumFractionDigits(2);
int choice = input.nextInt() ;
double transfee = 2.41 ;
double USrate = 0.9083 ;
double GBrate = 1.4015 ;
double YENrate = 0.0075 ;
if (choice > 3 || choice < 1) {
System.out.println("Invalid input!...... Please try agian\n");
} else {
if(choice == 1) {
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble() ;
double deuros = USamount * USrate ;
double ddisburse = deuros - transfee ;
System.out.print("\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ " + df.format(deuros) + "\n");
System.out.print("Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... " + df.format(ddisburse) + "\n" );
}else {
if(choice == 2){
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate ;
double gdisburse = geuros - transfee;
System.out.print("\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ " + df.format(geuros) + "\n");
System.out.print("Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... " + df.format(gdisburse) + "\n");
}else {
if(choice == 3){
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate ;
double ydisburse = yeuros - transfee ;
System.out.print("\nInput amount Yen:... " + YENamount + "\n");
System.out.print("Worth in euro's..... " + df.format(yeuros) + "\n");
System.out.print("Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. " + df.format(ydisburse) + "\n");
}
}
}
}
}
}
You could wrap your program with a while loop, which checks if the user entered 'y' at the end like this:
import java.text.DecimalFormat;
import java.util.Scanner;
class YourClassName
{
public static void main(String[] args)
{
boolean askAgain = true;
while (askAgain)
{
Scanner input = new Scanner(System.in);
System.out.println(
" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
int choice = input.nextInt();
double transfee = 2.41;
double USrate = 0.9083;
double GBrate = 1.4015;
double YENrate = 0.0075;
if (choice > 3 || choice < 1)
{
System.out.println("Invalid input!...... Please try agian\n");
} else
{
if (choice == 1)
{
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble();
double deuros = USamount * USrate;
double ddisburse = deuros - transfee;
System.out.print(
"\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ "
+ df.format(deuros) + "\n");
System.out.print(
"Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... "
+ df.format(ddisburse) + "\n");
} else
{
if (choice == 2)
{
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate;
double gdisburse = geuros - transfee;
System.out.print(
"\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ "
+ df.format(geuros) + "\n");
System.out.print(
"Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... "
+ df.format(gdisburse) + "\n");
} else
{
if (choice == 3)
{
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate;
double ydisburse = yeuros - transfee;
System.out.print("\nInput amount Yen:... "
+ YENamount + "\n");
System.out.print("Worth in euro's..... "
+ df.format(yeuros) + "\n");
System.out.print(
"Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. "
+ df.format(ydisburse) + "\n");
}
}
}
}
System.out.println("Do you want to do another calculation? (y/n)");
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
}
}
}
Setting the boolean variable to true first lets you enter the loop. The user will be asked as long as he types an y at the end. Every other character would exit the loop:
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
You could also check for explicit n, but that is up to you.
Put the code inside a while loop (while(true)). At the end of each if block
add one nested if.
System.out.print(Do you want to continue?");
if(in.next().equals("Y")) {
continue;
}
And you have add one extra menu(4th) for exit :
if(choice == 4){
break;
}
Related
This question already has answers here:
Using variables outside of an if-statement
(2 answers)
Closed 2 years ago.
I'm a student and would like to know if there is a way to take a variable out of its scope block to be used in a local scope? I am trying to code a store of some sort where the users are given a few options to choose what they want to buy, how much they want to buy, and give them the total payment for the same Item. Now outside the block scope, I want to give the overall total with how much they bought of each item. Here's my code:
import java.util.Scanner;
public class SariSariStore{
public static void main (String [] args) {
Scanner scanner = new Scanner(System.in);
int piattos = 20;
int wRabbit = 1;
int maxEM = 1;
int nescafeO = 7;
float iceW = 1.50f;
System.out.println("Would you like to buy something? [Y/N]");
char i = scanner.next().toLowerCase().charAt(0);
do {
System.out.println("==================================="
+"\n"+ "| Sari Sari Mart |"
+"\n"+ "==================================="
+"\n"+ "| What do you want to buy? |"
+"\n"+ "| |"
+"\n"+ "| 1) Piattos chips 20 Php |"
+"\n"+ "| 2) White Rabbit 1 Php |"
+"\n"+ "| 3) Max extra menthol 1 Php |"
+"\n"+ "| 4) Nescafe Original 7 Php |"
+"\n"+ "| 5) Ice water 1.5 PhP |"
+"\n"+ "| 6) Exit |"
+"\n"+ "===================================");
System.out.println("Please select option from the given choices: ");
int choice = scanner.nextInt();
if (choice >= 1 && choice <= 6){
if (choice == 1){
System.out.print("How many would you like to buy? " );
int quantity1 = scanner.nextInt();
int itotal1 = piattos * quantity1;
System.out.println("Total price: " + itotal1 +" Php");
}else if (choice == 2){
System.out.print("How many would you like to buy? " );
int quantity2 = scanner.nextInt();
int itotal2 = wRabbit * quantity2;
System.out.println("Total price: " + itotal2 +" Php");
}else if (choice == 3){
System.out.print("How many would you like to buy? " );
int quantity3 = scanner.nextInt();
int itotal3 = maxEM * quantity3;
System.out.println("Total price: " + itotal3 +" Php");
}else if (choice == 4){
System.out.print("How many would you like to buy? " );
int quantity4 = scanner.nextInt();
int itotal4 = nescafeO * quantity4;
System.out.println("Total price: " + itotal4 +" Php");
}else if (choice == 5){
System.out.print("How many would you like to buy? " );
int quantity5 = scanner.nextInt();
float itotal5 = iceW * quantity5;
System.out.println("Total price: " + itotal5 +" Php");
}else if (choice == 6){
}
}else{
System.out.println ("Sorry we do not have that item, please pick among the choices");
}
int Total = itotal1 +itotal2 +itotal3 +itotal4 +itotal6; // problematic statement
System.out.println ("Your total is:"+ Total + " Php");
System.out.println ("Do you still want to buy something? [Y/N]");
i = scanner.next().toLowerCase().charAt(0);
}while (i == 'y');
if (i =='n'){
System.out.println("Thank you! Please come again");
}
}
}
Thanks :>
Can't you use just one field for this? Like this:
System.out.println("Please select option from the given choices: ");
int choice = scanner.nextInt();
int total = 0;
if (choice >= 1 && choice <= 6){
if (choice == 1){
System.out.print("How many would you like to buy? " );
int quantity1 = scanner.nextInt();
total = piattos * quantity1;
System.out.println("Total price: " + total +" Php");
} else if (choice == 2){
System.out.print("How many would you like to buy? " );
int quantity2 = scanner.nextInt();
total = wRabbit * quantity2;
System.out.println("Total price: " + total +" Php");
} else if (choice == 3){
System.out.print("How many would you like to buy? " );
int quantity3 = scanner.nextInt();
total = maxEM * quantity3;
System.out.println("Total price: " + total +" Php");
}
...
} else {
System.out.println ("Sorry we do not have that item, please pick among the choices");
System.out.println ("Your total is:"+ total + " Php");
}
Also consider using switch statement for multiple if statements
This question already has answers here:
Unable to get total amount
(2 answers)
Closed 4 years ago.
I have designed a program which will rerun when the user enters "y" when asked if they wish to continue. The problem I am having is once the user enters "n" the program is supposed to display the total amount payable from all ticket options purchased. I have spent a couple of weeks stuck on this problem and am unsure of what to do next. I have only included the bottom part of my code. I have also included a photo to show my problem when the program is run.
here is my code:
package cse1pgx_a2;
import java.util.Scanner;
public class CSE1PGX_A2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int option, quantity, confirm;
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
float finalTotal = 0;
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
Scanner input = new Scanner(System.in);
while (continueLoop) {
System.out.println("\t"+ "##### Welcome to Zoos Victoria #####");
System.out.println("\t" + "\t" + "MAIN MENU" + "\n");
System.out.println("\t" + "Zoo has the following ticketing options" + "\n");
System.out.println("\t" + "1 = Child (4-6 yrs)");
System.out.println("\t" + "2 = Adult (16+ yrs)");
System.out.println("\t" + "3 = Senior (60+ yrs)" + "\n");
System.out.println("Enter your option:" );
option=input.nextInt();
switch (option) {
case 1:
System.out.println("Enter total No of tickets for Child:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " child tickets at " + childCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
case 2:
System.out.println("Enter total No of tickets for Adult:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " adult tickets at " + adultCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
default:
System.out.println("Enter total No of tickets for Senior:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " senior tickets at " + seniorCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
}
if (confirm !=1) {
System.out.println("Incorrect key!");
}
OUTER:
while (confirm == 1) {
switch (option) {
case 1:
childTotal=(int) ((double) quantity*childCost) ;
System.out.println("Total amount for child tickets: $" + childTotal);
break OUTER;
case 2:
adultTotal=(int) ((double) quantity*adultCost) ;
System.out.println("Total amount for adult tickets $" + adultTotal);
break OUTER;
default:
seniorTotal=(int) ((double) quantity*seniorCost);
System.out.println("Total amount for senior tickets $" + seniorTotal);
break OUTER;
}
}
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
} else {
continueLoop = false;
switch (option) {
case 1:
finalTotal=(float) ((double) childTotal+adultTotal+seniorTotal) ;
System.out.println("Total amount payable: $ " + finalTotal);
break;
default:
System.out.println("Error");
}
}
}
}
}
I have fixed issues and also updated code for better performance.
package test;
import java.util.Scanner;
public class CSE1PGX_A2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final float childCost = 18;
final float adultCost = 36;
final float seniorCost = 32.50F;
boolean continueLoop = true;
Scanner input = new Scanner(System.in);
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
while (continueLoop) {
int option, confirm=0;
System.out.println("\t ##### Welcome to Zoos Victoria #####");
System.out.println("\t \t MAIN MENU \n");
System.out.println("\t Zoo has the following ticketing options \n");
System.out.println("\t 1 = Child (4-6 yrs)");
System.out.println("\t 2 = Adult (16+ yrs)");
System.out.println("\t 3 = Senior (60+ yrs) \n");
System.out.println("Enter your option:");
option = input.nextInt();
switch (option) {
case 1: {
System.out.println("Enter total No of tickets for Child:");
int quantity = input.nextInt();
childTotal = quantity * childCost;
System.out.println("You are purchasing " + quantity + " child tickets at " + childCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for child tickets: $" + childTotal);
}
break;
}
case 2: {
System.out.println("Enter total No of tickets for Adult:");
int quantity = input.nextInt();
adultTotal = quantity * adultCost ;
System.out.println("You are purchasing " + quantity + " adult tickets at " + adultCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for adult tickets $" + adultTotal);
}
break;
}
case 3: {
System.out.println("Enter total No of tickets for Senior:");
int quantity = input.nextInt();
seniorTotal = quantity * seniorCost ;
System.out.println("You are purchasing " + quantity + " senior tickets at " + seniorCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for senior tickets $" + seniorTotal);
}
break;
}
}
if (confirm != 1) {
System.out.println("Incorrect key!");
}
System.out.println("Do you wish to continue? (Y/N) ");
char resume = input.next().charAt(0);
if (resume != 'y' && resume != 'Y') {
continueLoop = false;
System.out.println("Total amount for child tickets: $" + childTotal);
System.out.println("Total amount for senior tickets $" + seniorTotal);
System.out.println("Total amount for adult tickets $" + adultTotal);
float finalTotal = childTotal + adultTotal + seniorTotal ;
System.out.println("Total amount payable: $ " + finalTotal);
}
}
}
}
Try this code. I hope it helps.
public static void main(String[] args) {
int option, quantity, confirm; //minor change
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
float finalTotal = 0; //minor change
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
}else{
continueLoop = false;
switch (option) {
case 1:
finalTotal+=(double) quantity*childTotal ; //minor change
System.out.println("Total amount payable: $" + childTotal);
break;
case 2:
finalTotal+=(double) quantity*adultTotal ; //minor change
System.out.println("Total amount payable $" + adultTotal);
break;
default:
finalTotal+=(double) quantity*seniorTotal; //minor change
System.out.println("Total amount payable $" + seniorTotal);
break;
}
}
}
}
}
I wished to play and did not fully understand the problem...so i developed from scratch the application. Suryakant was faster so please accept his answer (if it solves your problem). I simply post this here since i worked on it :-)
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean continueLoop = true;
Map<TicketType, Integer> purchases=new HashMap<>();
do {
TicketType type = printMenu(scan);
System.out.println("Enter number of tickets for " + type.label);
int quantity = scan.nextInt();
System.out.println("You are purchasing "+quantity + " "+ type.label+ " ticket at "+type.cost+" each. " +
"Press 1 to confirm?");
int confirm= scan.nextInt();
if (confirm!=1) continue;
if (purchases.containsKey(type)){
purchases.put(type,purchases.get(type)+quantity);
System.out.println("You now have " +purchases.get(type) +" "+type.label +" tickets in total");
}else {
purchases.put(type,quantity);
}
System.out.println("You have added " +quantity +" "+type.label +" tickets in your basket.");
System.out.println("Do you wish to continue (Y|N)?");
String resume=scan.next();
if (resume.startsWith("Y") || resume.startsWith("y")){
continueLoop=true;
}else {
continueLoop=false;
}
}while (continueLoop);
System.out.println("Purchases");
long total=0;
for (Map.Entry<TicketType, Integer> ticketTypeIntegerEntry : purchases.entrySet()) {
System.out.println(ticketTypeIntegerEntry.getKey().label+"("+ticketTypeIntegerEntry.getValue()+")");
total+=ticketTypeIntegerEntry.getKey().cost*ticketTypeIntegerEntry.getValue();
}
System.out.println("Total payable ammount: "+total);
}
private static TicketType printMenu(Scanner scan) {
System.out.println("Welcome");
TicketType type;
int k = -1;
do {
for (TicketType ticketType : TicketType.values()) {
System.out.println(ticketType.id + ". for " + ticketType.label);
}
System.out.println("Enter your option");
k = scan.nextInt();
} while ((type=TicketType.valuefromId(k))==null);
return type;
}
private enum TicketType {
CHILD(1, "Child", 18D),
ADULT(2, "Adult", 36D),
SENIOR(3, "Senior", 18.5D);
int id;
String label;
double cost;
private static Map<Integer,TicketType> map=new HashMap<Integer,TicketType>();
static {
for (TicketType ticketType : TicketType.values()) {
map.put(ticketType.id,ticketType);
}
}
TicketType(int id, String label, double cost) {
this.id = id;
this.label = label;
this.cost=cost;
}
public static TicketType valuefromId(int id){
return map.get(id);
}
}
}
improvements are in reading.. i would check first if what i read is character or not..
I am trying to write a program that ask a user for 2 numbers and then ask the user to pick a command from a menu by entering the correspond number to the command.
I can write the program if i take the input as an Int but cannot figure it out for a string, also it has to be a string.
I am having problems when it enters the while loop to validate the user input it does not stop when the statement is false it will stay in the loop I can not figure out what i am doing wrong.
Here is the code i have.
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
System.out.println();
while (!input.equals(1) && !input.equals(2) && !input.equals(3) && !input.equals(4)) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
System.out.println();
if (input.equals(1)) {
System.out.print(L + " * " + R + " = " + (L * R));
} else if (input.equals(2)) {
System.out.print(L + " / " + R + " = " + (L / R));
} else if (input.equals(3)) {
System.out.print(L + " + " + R + " = " + (L + R));
} else {
System.out.print(L + " - " + R + " = " + (L - R));
}
}
stdIn.close();
}
}
Any help would be much appreciated.
Thank you in advanced.
The line input = stdIn.next(); is taking input as String
while your comparison is against integer. So a String never equals Int
You may try changing your while loop condition to:
while (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4"))
note the double quote around the numbers
Is answered, but check this
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
while (true) {
if (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4")) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
} else {
if (input.equals("1")) {
System.out.print(L + " * " + R + " = " + (L * R));
break;
} else if (input.equals("2")) {
System.out.print(L + " / " + R + " = " + (L / R));
break;
} else if (input.equals("3")) {
System.out.print(L + " + " + R + " = " + (L + R));
break;
} else {
System.out.print(L + " - " + R + " = " + (L - R));
break;
}
}
}
stdIn.close();
}
}
This is my basic currency converter for my intro to java class. I'm supposed to be able to convert between yen, dollars, pounds and euros using static rates. It works, but I was curious to know if I did it in the most efficient way possible. It seems quite long and looks like a huge mess. Just wanting some feedback.
import java.util.Scanner;
public class currency
{
public currency()
{
char us_dollar_sym = 36;
char pound_sym = 163;
char yen_sym = 165;
char euro_sym = 8364;
String us_dollar = "Dollars";
String pound = "Pounds";
String yen = "Yen";
String euro = "Euros";
double rate = 0;
// Interface
System.out.println("Welcome to the Currency Converter Program \n");
System.out.println("Use the following codes to input your currency choices: \n 1 - US dollars \n 2 - Euros \n 3 - British Pounds \n 4 - Japanese Yen \n");
//
System.out.println("Please choose the input currency:");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
String inType = null;
switch(choice) {
case 1: inType = "US Dollars >> " + us_dollar_sym; break;
case 2: inType = "Euros >> " + euro_sym; break;
case 3: inType = "British Pounds >> " + pound_sym; break;
case 4: inType = "Japanese Yen >> " + yen_sym; break;
default:
System.out.println("Please restart the program & enter a number from the list.");
return;
}
System.out.println("Please choose the output currency");
int output = in.nextInt();
System.out.printf("Now enter the input in " + inType);
double input = in.nextDouble();
if (choice == output)
System.out.println("Same currency no need to convert");
if (choice == 1 && output == 2)
{
double dollar_euro_rate = 0.78391;
rate = input * dollar_euro_rate;
System.out.printf( "%s" + input + " at a conversion rate of " + dollar_euro_rate + " Dollars to %s = %.2f\n", (char)us_dollar_sym, euro, rate);
}
else if (choice == 1 && output == 3){
double dollar_pound_rate = 0.621484;
rate = input * dollar_pound_rate;
System.out.printf( "%s" + input + " at a conversion rate of " + dollar_pound_rate + " Dollars to %s = %.2f\n", (char)us_dollar_sym, pound, rate);
}
else if (choice == 1 && output == 4){
double dollar_yen_rate = 107.174;
rate = input * dollar_yen_rate;
System.out.printf( "%s" + input + " at a conversion rate of " + dollar_yen_rate + " Dollars to %s = %.2f\n", (char)us_dollar_sym, yen, rate);
}
if (choice == 2 && output == 1)
{
double euro_dollar_rate = 1.27579;
rate = input * euro_dollar_rate;
System.out.printf( "%s" + input + " at a conversion rate of " + euro_dollar_rate + " Euros to %s = %.2f\n", (char)euro_sym, us_dollar, rate);
}
else if (choice == 2 && output == 3)
{
double euro_pound_rate = 0.792648;
rate = input * euro_pound_rate;
System.out.printf( "%s" + input + " at a conversion rate of " + euro_pound_rate + " Euros to %s = %.2f\n", (char)euro_sym, pound, rate);
}
else if (choice == 2 && output == 4)
{
double euro_yen_rate = 136.708;
rate = input * euro_yen_rate;
System.out.printf( "%s" + input + " at a conversion rate of " + euro_yen_rate + " Euros to %s = %.2f\n", (char)euro_sym, yen, rate);
}
if (choice == 3 && output == 1)
{
double pound_dollar_rate = 1.60972;
System.out.printf( "%s" + input + " at a conversion rate of " + pound_dollar_rate + " Pounds to %s = %.2f\n", (char)pound_sym, us_dollar, rate);
}
else if (choice == 3 && output == 2)
{
double pound_euro_rate = 1.26161;
System.out.printf( "%s" + input + " at a conversion rate of " + pound_euro_rate + " Pounds to %s = %.2f\n", (char)pound_sym, euro, rate);
}
else if (choice == 3 && output == 4)
{
double pound_yen_rate = 172.511;
System.out.printf( "%s" + input + " at a conversion rate of " + pound_yen_rate + " Pounds to %s = %.2f\n", (char)pound_sym, yen, rate);
}
if (choice == 4 && output == 1)
{
double yen_dollar_rate = 0.00932574;
System.out.printf( "%s" + input + " at a conversion rate of " + yen_dollar_rate + " Yen to %s = %.2f\n", (char)yen_sym, us_dollar, rate);
}
else if (choice == 4 && output == 2)
{
double yen_euro_rate = 0.00730615;
System.out.printf( "%s" + input + " at a conversion rate of " + yen_euro_rate + " Yen to %s = %.2f\n", (char)yen_sym, euro, rate);
}
else if (choice == 4 && output == 3)
{
double yen_pound_rate = 0.00579135;
System.out.printf( "%s" + input + " at a conversion rate of " + yen_pound_rate + " Yen to %s = %.2f\n", (char)yen_sym, pound, rate);
}
System.out.println("Thank you for using the currency converter");
}
}
I am always cautious of using integer input. If someone types a char, your program would likely crash as an exception would occur. Accepting a char of the number might be a safer alternative.
When you check the "choice" and "output" in the same if statement it requires more resources. Nesting the if statements might improve efficiency. This would be having the if statement for choice with the if statements for output within them.
Since you refer to your currency as int, I would use an n by m matrix for storing the exchange rate. n would be the first currency and m the second. With both int you can retrace the correct exchange rate.
The diagonal in the matrix would be 1 (since USD >> USD =1 ).
Finally, write a function to compute the exchange rate and return the corresponding text (you can use an hashmap for that, with the int as a key and the name ( string) as the value)
exchange_rate = currency[1][2];
HashMap hm = new HashMap();
hm.put(1, new string("USD");
etc...
Express all of your rates as a multiplier of one standard value, for instance use the USD as the standard value. Then the conversion values for GBP would be 1.60, the USD would be 1.0 and the Euro would be 1.29. Then the conversion calculation would be:
From Value * From Conversion * 1/To Conversion
For instance from 1 GBP to Euro would be:
1 * 1.60 * (1/1.29) = 1.24
If you store all of your rates in a HashMap then you can avoid the switch statements completely.
Why you are using this way to convert currency. You have the JSR 354 Money and Currency API here are some examples you can use, its really easy to use and fast:
MonetaryAmount monetaryAmount = Money.of(100.20, usd);
CurrencyUnit currency = monetaryAmount.getCurrency();
NumberValue numberValue = monetaryAmount.getNumber();
int value= numberValue.intValue();
I am attempting to simplify my long code of a calculator program, but I have a road block. I have a new else if statement for each calculator operator, but what I want to do is allow the user to manually type in, on one line, the entire operation they would like to perform and have the code compute it.
Here's what I have:
do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();
if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 * num2;
System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);
answer = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");
This is what I want the output to be:
Enter operation:
4 * 6
4 * 6 = 24
Should be able to enter any operation here on one line. I am not asking you to write my calculator for me, I am asking how to allow the computer to read in the entire operation off one line and compute it, then print it.
If you use scanner readLine then you can read a whole line
e.g.
4 * 6
This line can then be split to get three tokens
String tokens [] = line.split (" ");
then you can see what operation to do based upon token[1]
if (token[1].equals ("-") {
//lets minus token[2] from token[0]
// need to convert String to Number
}
You can use String.split and store it in an array. Then it will return an array of string, parse those back to integers. the do the operation you want. The x variable will be the result.
if(maininput.contains("+")) {
String[] stringarr = string.split("\\+");
int x = Integer.parseInt(stringarr[0]) + Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " + " + stringarr[1] + " = " + x);
} else if(maininput.contains("-")) {
String[] stringarr = string.split("\\-");
int x = Integer.parseInt(stringarr[0]) - Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " - " + stringarr[1] + " = " x);
}
... And so on.
You could try parsing the line using a Pattern object, something like this:
Pattern opPattern = Pattern.compile("(\\d+) *([+-*/]) *(\\d+)");
Matcher matcher = opPattern.matcher(userLine);
if(matcher.find()) {
int op1 = Integer.toValue(matcher.group(1));
int op2 = Integer.toValue(matcher.group(3));
String op = matcher.group(2);
if(op.equals("+")) {
// do + op ...
} else ... {
// etc...
}
} else {
// error in line, not the form of an operation
}
Have a look at the javadoc, as I'm not sure if I used the correct method names and the like, just tried to illustrate the idea...