1
votes

I am making a basic currency converter which takes a users choice of currency and converts the amount, obviously not finished as I have ran into this problem. Help and pointers would be appreciated.

import java.util.Scanner;

class Converter {
    public static void main(String args[]){
        double PLN;
        double GDP;
        System.out.println("Which currency do you wish to convert?");
        System.out.println("Press a corresponding number");
        System.out.println("1. Great British Pound (GDP) £");
        System.out.println("2.Polish zloty (PLN) zl");

        Scanner option = new Scanner(System.in);

        if (option = 1){            

        }       
    }   
}

Error

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Type mismatch: cannot convert from Scanner to boolean Type mismatch: cannot convert from int to Scanner at Converter.main(Converter.java:14)

2

2 Answers

2
votes

It should be more like

Scanner option = new Scanner(System.in);
String userInput = option.nextLine();

if (userInput.equals("1")){            
    // ...
}

A few things wrong here:

  1. Testing for equality is ==, NOT =. You're trying to assign 1 to the Scanner object.
  2. The Scanner itself is not actually a string. You need to call readLine on it.
  3. Even if the Scanner was a string, you can't compare a String to an int.
  4. You need to use .equals for strings, since == in Java always compares by reference, not by value. == basically means "are these two objects the exact same object," not "do these two objects look the same."

An alternative way is to use nextInt:

Scanner option = new Scanner(System.in);

while (!option.hasNextInt()) {
    System.out.println("Bad input"); // print an error message
    option.nextLine(); // clear bad input
}
int userInput = option.nextInt();
if (userInput == 1) {
    // ...
}

Also note that you can use a switch statement for cases like these:

int userInput = option.nextInt();
switch(userInput) {
case 1:
    // the user input was 1
    break;
case 2:
    // it was 2
    break;
// ...
default:
    // it was not any of the cases
}

You can use switches on strings, but only in Java 7 or above.

0
votes

You could.... change your initial condition from this:

if (option = 1) //??

to this:

System.out.println("Enter int: ");
if ((option.nextInt()) == 1)
//do something