Currency Exchanger - java

I am trying to write a code that will exchange between AED,MYR,USD. I got to the following code and I cant fix the error.
It looked like the system.in isn't closing so I wrote the inclose(). But I still get the same results.
My problem might be something else and am not seeing it.
EDIT: this is the current code with changes.
import java.util.Scanner;
public class CurrencyConverter
{
protected static long amount;
static long Namount ;
static int commesion;
static String to;
public static void main( String[] args )
{
CurrencyConverterM MSg=new CurrencyConverterM();
CurrencyConverterM account1 = new CurrencyConverterM( );
String from ;
for(int i=0 ;i<3; i++)
{
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
//in.close();
if ("USD".equals(from)) {
amount=((long) (amount*0.27));
amount=account1.converter(to, amount);
}
else if ("MYR".equals(from)) {
amount=((long) (amount * 1.14));
amount =account1.converter(to, amount);
}
else {
if(mmount >= 900) {
Namount = (amount-50);
commesion =50;
}
else
{
Namount = (amount - 10);
commesion = 10;
}
}
System.out.println(MSg.getMsg());
}
}
}
the output should be as follows.
asking for current currency:
asking to what currency u want it:
asking about the amount.
am converting any amount to AED so I make it the main unit, then converting to the wished unit.
EDIT
public class CurrencyConverterM extends CurrencyConverter
{
long am;
#SuppressWarnings("static-access")
long converter (String to,long amount)
{
if ("MYR".equals(to)) {
am=(super.amount*=0.88);
}
else if ("MYR".equals(to)) {
am=(super.amount*=3.7);
}
return am ;
}
#SuppressWarnings("static-access")
public String getMsg()
{
return ("Thank you. The converted amount is "+(super.amount) + ". We will take" +super.commesion + " commission, and you will get "+ super.Namount);
}
}
before it didn't read the user's input, now its not converting the values.
I tried to print out my vales after each calculation but it looks like that the variable am is not being calculated correctly and its being multiplied by a 0 or divided by one ( the last result is always 0 ) but the amount that is in the main class is not 0 and its not converted to AED as well.
So I am getting this :Thank you. The converted amount is 0.0 1000.0. We will take50 commission, and you will get 0.0

String comparison is wrong.
from=="MYR" should be from.equals("MYR") rather I would recommend equalsIgnoreCase which is not case sensitive.

You should call scanner.nextLine() (in.nextLine()) and not in.toString()
Also you can use the same scanner and not to create 3 different scanners.
See the following part of your code updated with one Scanner (in):
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
System.out.println(from + " " + to);
in.close();
by doing in.nextLine() you read the next line of user input.
From java 8 javadocs:
nextLine
public String nextLine()
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
The above will solve the issue that no input is read by your code.
Later you will have issues comparing the String user entered:
from=="USD" should be changed to "USD".equals(from)
Tip: Prefer to use "String".equals(variable) to avoid null pointer exceptions when variable is null.

Related

What is the best way to have keyboardIn.nextInt() in Java Scanner to ignore a '$' sign without altering .nextInt?

So this is currently what I have right now!
int downPayment;
System.out.printf("How much will the down payment be?: ");
Scanner keyboardIn = new Scanner(System.in);
downPayment = keyboardIn.nextInt();
System.out.println(downPayment);
However, if I were to have a user enter ' $500 ', the build would fail (as scanner 'scans' for only an integer).
Is there a way to use scanner where it would ignore the first index of an 'integer', as I think that having scanner look at the variable as a string and converting the dollar value to an int while appending the first index is super inefficient.
Thanks!
I think that having scanner look at the variable as a string and converting the dollar value to an int while appending the first index is super inefficient.
Drawing conclusions from thinking is for philosophers, not engineers.
Here's your proposed efficient version:
import java.util.*;
class NextInt {
public static void main(String[] args) {
Scanner keyboardIn = new Scanner(System.in);
int downPayment;
for(int i=0; i<10000000; i++) {
downPayment = keyboardIn.nextInt();
}
}
}
Here's your proposed super inefficient version:
import java.util.*;
class AsString {
public static void main(String[] args) {
Scanner keyboardIn = new Scanner(System.in);
int downPayment;
for(int i=0; i<10000000; i++) {
String input = keyboardIn.next();
if (input.startsWith("$")) input = input.substring(1);
downPayment = Integer.parseInt(input);
}
}
}
We can generate 10 million lines of test data:
yes '1500' | head -n 10000000 > nodollar
yes '$500' | head -n 10000000 > dollar
Now benchmark it (best of 3):
$ time java NextInt < nodollar
real 0m3.544s
user 0m3.759s
sys 0m0.124s
$ time java AsString < dollar
real 0m2.530s
user 0m2.735s
sys 0m0.111s
As it turns out, not only are we talking about upper bound of ~0.4 microseconds saved time per user input, but you are spending your time and effort on a slower implementation. No wonder they say that premature optimization is the root of all evil!
Anyways, that was a tangent that doesn't actually answer the question. Have you considered using skip to skip an optional $?
keyboardIn.skip("[$]?");
downPayment = keyboardIn.nextInt();
Instead of making your program work for users who enter a dollar sign at the start of their number, one option is to tell the user more clearly that they are expected to enter just the number itself. If you put a $ symbol at the end of the prompt, the user will be typing immediately after that $; any sensible user will realise they are not supposed to type an extra $, because it would be visibly wrong on the screen to have two $ signs next to each other.
If anybody is silly enough to type an extra $ anyway, let them see an error message.
System.out.print("How much will the down payment be?: $");
A simple change. Note also that you don't need printf here, just print is sufficient.
This obviously doesn't handle every case, but you could check if the first value is a '$' character, if so remove it, then check if the remaining String can be parsed as an int:
public static void getDownPaymentValue() {
Scanner sc = new Scanner(System.in);
System.out.print("How much will the down payment be?: ");
String input = sc.next();
String validatedInput = validateUserInput(input);
int downPayment = 0;
if(isInteger(validatedInput)) {
downPayment = Integer.parseInt(validatedInput);
} else {
System.out.println("Value is not of type int.");
}
System.out.println("Validated input is: " + validatedInput);
}
public static String validateUserInput(String str) {
int dollarSignIndex = str.indexOf("$");
if(dollarSignIndex == 0) {
str = str.substring(1);
}
return str;
}
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
You could use one of:
downPayment = Integer.parseInt(keyboardIn.next().replace("$",""));
downPayment = Integer.parseInt(keyboardIn.next().substring(1));
But I don't know if it's the "best way".
If you really must keep your nextInt(), you can catch the exception:
try {
downPayment = keyboardIn.nextInt();
} catch (InputMismatchException ex) {
// handle it
downPayment = Integer.parseInt(keyboardIn.next().replace("$",""));
}
But I don't think it's generally advised to handle any RuntimeException.

Can't figure out of how to stop the application when a specific String value match a specific condition

It's my first time posting some topic on this website, and running on a problem that I can't get over it. The following problem that I'm stunning into is as followed:
When the total calculation of the above decimal numbers meets a specific target amount, print: "Congratulations" if not, print:"Calculation error", after they input the string word: "Ready". when a user inputs a string called: "I Quit!", the application will exit and prints: "Quitter".
Here is the Java code that I currently have:
public static void goal(double targetAmount) {
Scanner sc = new Scanner(System.in);
double total = 0;
while (scanner.hasNextDouble()) {
double input= sc.nextDouble();
total += input;
}
String inputString = sc.next();
}
I'm looking forward to see your response. Hope I've formulate my question properly?
I think the problem is the input you read using scanner.next(), because scanner.next() reads the input till the next blank character. Which means it will just read I when you enter I Quit!.
Printing the output of the variable input shows the problem:
public static void main(String[] args) {
salarisdoel(100);
}
public static void salarisdoel(double targetAmount) {
Scanner scanner= new Scanner(System.in);
double total = 0;
while (scanner.hasNextDouble()) {
double inputMoney= scanner.nextDouble();
total += inputMoney;
}
String input = scanner.next();
System.out.println(input);//print to check what was read from the console
switch (input) {
case "I Quit!":
System.out.println("Quitter");
break;
case "Ready":
if (total>= targetAmount) {
System.out.println("Congratulations");
} else {
System.out.println("Calculation Error");
}
break;
default:
System.out.println("Something went wrong. Try again!");
break;
}
}
If you use a string without a blank space for quitting (e.g. "I_Quit!") it will work.
You can use System.exit() to exit the program.
case "I Quit!":
System.out.println("Quitter");
System.exit();

When user presses "enter" key or space enter then error message pops up

I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".

StringOutOfBoundsException 1 Java

This is what the error says:
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at FracCalc.produceAnswer(FracCalc.java:34)
at FracCalc.main(FracCalc.java:16)
And Here is my existing code:
import java.util.*;
public class FracCalc {
public static void main(String[] args)
{
// TODO: Read the input from the user and call produceAnswer with an equation
Scanner input = new Scanner(System.in);
System.out.println("Do you want to calculate something? If no, type in 'quit'. If yes, simply type in 'yes'. ");
String Continue = input.next();
if(Continue.equals("quit")){
System.out.println("Have a nice day! ");
}else if(Continue.equals("yes")){
System.out.println("Please input a fraction, there must be exactly one space between the operator and the operand. ");
String readInput = input.nextLine();
System.out.println(produceAnswer(readInput));
}
}
// ** IMPORTANT ** DO NOT DELETE THIS FUNCTION. This function will be used to test your code
// This function takes a String 'input' and produces the result
//
// input is a fraction string that needs to be evaluated. For your program, this will be the user input.
// e.g. input ==> "1/2 + 3/4"
//
// The function should return the result of the fraction after it has been calculated
// e.g. return ==> "1_1/4"
public static String produceAnswer(String input)
{
// TODO: Implement this function to produce the solution to the input
int space = input.indexOf(" ");
int nextspace = space + 2;
String operand = input.substring(0, space + 1);
String operator = input.substring(space + 1, nextspace);
String operand2 = input.substring(nextspace + 1, input.length());
return operand2;
}
// TODO: Fill in the space below with any helper methods that you think you will need
}
I'm trying to segregate fraction operators by determining the indexes of spaces and then going from there. Unfortunately i keep getting this error. Can someone please help! Thank You!
You have to use input.nextLine() since you want to read the entire line and not just characters. Try this in your main method:
Scanner input = new Scanner(System.in);
System.out.println("Do you want to calculate something? If no, type in 'quit'. If yes, simply type in 'yes'. ");
String Continue = input.nextLine();
if (Continue.equals("quit")) {
System.out.println("Have a nice day! ");
} else if (Continue.equals("yes")) {
System.out.println(
"Please input a fraction, there must be exactly one space between the operator and the operand. ");
String readInput = input.nextLine();
System.out.println(produceAnswer(readInput));
}

Java code suddenly stop

Ive got a problem.I 'm new to Java,I've started today:D) ..I've programmed before so I know it little bit,but I am new to Java. Here is my code: `
public class Tutorial {
public static void main(String[] args) {
double num1,num2;
String operacia;
Scanner in=new Scanner (System.in);
System.out.println("Write 2 numbers");
num1=in.nextDouble();
num2=in.nextDouble();
System.out.println("Choose the operation");
operacia=in.nextLine();
if (operacia.equals("+")){
System.out.println("Your result is "+(num1+num2)) ;
}
else if (operacia.equals("-")){
System.out.println("Your result is "+(num1-num2)) ;
}
else if (operacia.equals("/")){
System.out.println("Your result is "+(num1/num2)) ;
}
else if (operacia.equals("*")){
System.out.println("Your result is "+(num1*num2)) ;
}
}
}`
It wants from me 2 numbers,I write them and them it writes "Choose the operation" and its over.No more inputs.Thank you very much :)
Your problem is simple.
Just replace the code with next() instead of nextLine().Effectively, the line your code is returning is receiving is a blank line. Hence when it reaches the conditional statement it has an empty string and terminates.
next()
Finds and returns the next complete token from this scanner.
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
Your code should be fixed by a simple change.
public static void main(String[] args) {
double num1,num2;
String operacia;
Scanner in=new Scanner (System.in);
System.out.println("Write 2 numbers");
num1=in.nextDouble();
num2=in.nextDouble();
System.out.println("Choose the operation");
operacia=in.next();
if (operacia.equals("+")){
System.out.println("Your result is "+(num1+num2)) ;
}
else if (operacia.equals("-")){
System.out.println("Your result is "+(num1-num2)) ;
}
else if (operacia.equals("/")){
System.out.println("Your result is "+(num1/num2)) ;
}
else if (operacia.equals("*")){
System.out.println("Your result is "+(num1*num2)) ;
}
}
Scanner#nextDouble() consumes only the next token as a double from the input. It does not consume the new line you typed using the Enter on the keyboard while entering the two numbers. When the execution reaches operacia=in.nextLine();, this new line is consumed, never allowing the user a chance to type the operating string.
To solve this, you need to read the whole line using Scanner#nextLine() and convert it to a double:
String input = in.nextLine();
num1 = Double.parseDouble(input);
input = in.nextLine();
num2 = Double.parseDouble(input);
I believe the in.nextLine(); operation is reading only to the end of the line where you input 2 numbers. If you want your program to only consider the next line, you have to clear the current one first.
Try this, it should work:
System.out.println("Choose the operation");
in.nextLine(); //clear the current line
operacia=in.nextLine();

Categories