Basic Currency Converter - Looking for feedback - java

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();

Related

How do I fix my looping for this Single Player Dice Game (4 - 4 sided die)? Issues with Scanner input not yielding correct outputs

// I've been working on this all day but still seem to be stuck.
// I'm not getting any obvious errors but the looping seems to be broken.
// I'm a beginner so its very likely I missed something big but just overlooked it.
// This assignment is due at midnight for my class lol.
// I feel like I constructed the base format decently however my unfamiliarity with using loops is really throwing me for one. I've looked online elsewhere but many of the "dice" programs people have made only pertain to one 6-sided die and do not involve a turn based user input.
// Any useful tips would be fantastic, is there a more efficient way to go about constructing this game? I know creating multiple classes would have cleaned up the look of the program but I'm really only looking for functionality at the moment.
package prgm06;
import java.util.Scanner;
public class DiceGame
{
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
System.out.println("Do you wish to play? [y,n]: ");
do { // I always want the dice to roll unless "n" is selected.
answer = stdIn.next();
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
}
while(answer.equalsIgnoreCase("y")); // issues with "y" not printing if/ else statements
{
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) && (d1 == d3) && (d1 == d4))
{
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
}
else
{
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
}
// do
{
answer = stdIn.next(); // I'm not sure if i need to keep using this at each segment
}
for(answer.equalsIgnoreCase("n");; // will not print on first user input of "n".
{
// System.out.println();
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
if (userWin > userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " Good Job!");
System.out.println(turnCounter + " Rounds played.");
}
else if (userWin < userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " You shouldn't bet money on this game...");
System.out.println(turnCounter + " Rounds played.");
}
else
{
System.out.println("Your win/loss ratio is: 1.0 .");
System.out.println(turnCounter + " Rounds played.");
}
break;
}
}
}
I've edited your code. Some errors were related to syntax, and some were possibly related to the logical flows. This should work as a base, and you can modify and improve it as you see fit:
import java.util.Scanner;
public class DiceGame {
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
do { // I always want the dice to roll unless "n" is selected.
System.out.println();
System.out.println("Do you wish to play? [y,n]: ");
answer = stdIn.next();
if (answer.equalsIgnoreCase("y")) {
turnCounter++;
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) || (d1 == d3) || (d1 == d4) || (d2 == d3) || (d2 == d4) || (d3 == d4) {
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
} else {
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
System.out.println("Your win/loss ratio is: " + userWin + ":" + userLose);
if (userWin > userLose) {System.out.println("Good Job!");}
if (userWin < userLose) {System.out.println("You shouldn't bet money on this game...");}
System.out.println(turnCounter + " Rounds played.");
}
} while(answer.equalsIgnoreCase("y"));
}
}
Some points to note:
The game will keep running as long as the user types in 'y', since that is your condition: answer.equalsIgnoreCase("y").
I changed the win condition logic to check for at least a pair using the logical OR operator
I removed the division operator for the ratio result for win/loss and just replaced it with a display of wins:losses; This could be changed if you want it to calculate for an actual percentage or decimal value, but you have to check for cases where losses == 0 to prevent a divide by zero error
The Do-While loop should encompass all of the gameplay from start to finish, so the question that asks you to play again should go at the start or at the end of this loop (I placed it at the start)

How to Fix: "Must be an array type but is resolved to a string"

Creating a program that uses a menu to call separate modules of a simple health tracker for a beginner programming course.
Would appreciate some help concerning the exact reason why the array isn't working properly and is "resolved to a string"
I have a lot more to add before i can submit the program but this is holding me up.
It is in Module 3, the line attempting to recall the array
I'm leaving the entire code so far here because I don't understand what I've done wrong and am hoping this place is more helpful than the useless forums at uni.
public class HealthMate {
double bmi, bmr, heightM, weightKG;
int age, week = 7, days = 1;
int calories[] = new int[days];
int menuChoiceInt;
char genderChar;
boolean male;
public static void main(String[] args) {
HealthMate firstObj = new HealthMate();
firstObj.menu();
}
public void menu() {
while (menuChoiceInt != 4) {
String menu = "HealthMate Alpha 0.1 \n " + "Please make a numerical selection \n";
menu += "[1] Enter or Update your Details\n";
menu += "[2] Return BMI and BMR \n"; // menu options call different modules
menu += "[3] Weekly Tracker and Advice \n";
menu += "[4] Exit \n";
String menuChoiceString = JOptionPane.showInputDialog(menu);
menuChoiceInt = Integer.parseInt(menuChoiceString);//
if (menuChoiceString != null) {
if (menuChoiceInt == 1) {
genderChar = JOptionPane.showInputDialog("Please Enter your Gender as either M or F").charAt(0);
heightM = Double.parseDouble(
JOptionPane.showInputDialog("Enter Height in Meters,\n eg 1.73 for 173 cm.: "));
if (heightM <= 0) {
heightM = Double.parseDouble(JOptionPane.showInputDialog("Error! Enter a postitive number"));
}
weightKG = Double.parseDouble(JOptionPane.showInputDialog("Enter Weight in Kilograms"));
if (weightKG <= 0) {
weightKG = Double.parseDouble(JOptionPane.showInputDialog("Error! Enter a postitive number"));
}
bmi = weightKG / Math.pow(heightM, 2.0);
male = genderChar == 'M';
if (male) {
bmr = (10 * weightKG) + (62.5 * heightM) - (5 * age) + 5;
} else {
bmr = (10 * weightKG) + (62.5 * heightM) - (5 * age) - 161;
JOptionPane.showMessageDialog(null,"Your Specific BMI and BMR have been ");
menuChoiceInt = Integer.parseInt(menuChoiceString);// recall menu
}
}
if (menuChoiceInt == 2) if (bmi < 18.5) {
JOptionPane.showMessageDialog(null,
"Your BMI is " + bmi + ", You are underweight.\n" + "Your BMR is " + bmr);
} else if (bmi < 25) {
JOptionPane.showMessageDialog(null, "Your BMI is " + bmi
+ ", You are within the healthy weight range.\n" + "Your BMR is " + bmr);
} else if (bmi < 30) {
JOptionPane.showMessageDialog(null,
"Your bmi is " + bmi + ", You are overweight\n" + "Your BMR is " + bmr);
} else {
JOptionPane.showMessageDialog(null,
"Your bmi is " + bmi + ", You are Obese" + "Your BMR is " + bmr);
}
JOptionPane.showMessageDialog(null,
"This module is supposed to recall your BMI and BMR \n"
+ "and give general advice on health.");
{
menuChoiceInt = Integer.parseInt(menuChoiceString);
}
if (menuChoiceInt == 3) {
while (days > week) {
calories[week] = Integer.parseInt(JOptionPane.showInputDialog("Enter Calories for day"[days]);// employee salary
days = days + 1;
JOptionPane.showMessageDialog(null,
"This module is supposed to store data in an array over the course \n"
+ "of a week to show you your pattern of intake vs output.");
}
{
menuChoiceInt = Integer.parseInt(menuChoiceString);
}
} else if (menuChoiceInt == 4) {
}
}
}
}
}
I'm trying to get the calorie input to be saved over the course of 7 days so I can average it out, compare it to BMR and Activity level and give general advice on whether you are in surplus or deficit of calorie intake.
PS: Maybe if you have years of experience don't start your reply with "Well its obvious that..." and continue your mockery of someone who started programming less than a month ago as you people so often seem to on this website.
You have int days = 1, but you use it as [day] - this is incorrect in java:
calories[week] = Integer.parseInt(JOptionPane.showInputDialog("Enter Calories for day " + days));

Looping program back to ''menu''

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;
}

Simple Calculator Operation

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...

if statement never executed

Why doesn't this code enter into the if statement?
public class GradeCalculator {
public static void main(String[] args) {
/*
* A 900 - 1000(90% to 100%) B 800 - 899(80% to 89%)
* C 700 - 799(70% to 79%) D 600 - 699(60% to 69%)
* F 599 and below (Below 60%)
*/
String Name = JOptionPane.showInputDialog("Please enter your name: ");
String pointsEarned = JOptionPane.showInputDialog("Please enter the points earned: ");
String possiblePoints = JOptionPane.showInputDialog("Please enter the total points possible: ");
double pe = Double.parseDouble(pointsEarned);
double pp = Double.parseDouble(possiblePoints);
double grade = (pe/pp)*100;
char LetterGrade;
if(grade>=900){
LetterGrade = 'A';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you for an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
}
}
}
You have calculated percentage that will not be above 100.Therefore just change if condition to
if (grade>=90)
You can simply debug and see what happens there.Add else block and see value of grade.
if(grade>=900){
LetterGrade = 'A';
// ....
}else{
System.out.print(grade);
}
Your grade variable is a percentage and you are comparing it as if it were the score you calculated the percentage on. So it looks like what you want is just to use pe instead of the grade variable.
if(pe>=900){
then only calculate percentage when displaying
double percentage = (pe/pp)*100
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + percentage + "%" + " and you for an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
Either that or consider grade variable as percentage when testing it
if (grade>=90) //90%
Also
Variables should always start with a lowercase letter so LetterGrade should be letterGrade
That's how I solved it.
import javax.swing.JOptionPane;
public class GradeCalculator
{
public static void main(String[] args)
{
boolean exitLoop = false;
while(exitLoop == false)
{
String Name = JOptionPane.showInputDialog("Please enter your name: ");
String pointsEarned = JOptionPane.showInputDialog("Please enter the points earned: ");
String possiblePoints = JOptionPane.showInputDialog("Please enter the total points possible: ");
double pe = Double.parseDouble(pointsEarned);
double pp = Double.parseDouble(possiblePoints);
double grade = (pe*100)/pp;
double Lgrade = pe;
char LetterGrade;
if(Lgrade >= 900)
{
LetterGrade = 'A';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
} else if (Lgrade <899 && Lgrade >=800)
{
LetterGrade = 'B';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
} else if (Lgrade <799 && Lgrade >=700)
{
LetterGrade = 'C';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
} else if (Lgrade <699 && Lgrade >=600)
{
LetterGrade = 'D';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
} else if(Lgrade <599)
{
LetterGrade = 'F';
JOptionPane.showMessageDialog(null, Name + " your grade percentage you earned is " + grade + "%" + " and you got an " + LetterGrade, "Your Grades", JOptionPane.PLAIN_MESSAGE);
}
int selectedOption = JOptionPane.showConfirmDialog(null, "Do you want to run the program again?", "Yes or No", JOptionPane.YES_NO_OPTION);
if(selectedOption == JOptionPane.YES_OPTION)
{
exitLoop = false;
}
else
{
exitLoop = true;
}
}
}
}

Categories