Rae
Rae

Reputation: 83

How can i compare string and character types?

    System.out.print("Enter C for Celsius or F for Farenheit: ");
    String optionLetter = kb.readLine();

    if (optionLetter == 'c')
    {
        System.out.print("Enter temperature: ");
        double tempC = Integer.parseInt(kb.readLine());

        double degreesF = (9 * (tempC/5) +32);

        System.out.println(tempC + " celcius is " + degreesF + " in farenheit.");
    }
}

so the user can input only one character either C or c....so basically in the readLine, it cant read Character data types...so i am force to declare it in string but when i use it in a condition in the if statement i get the error during compiling that string and char are incompatible types... i know its incompatible but what can i do??? i cant declare the variable optionLetter as character and also i just need to check if the user input c????

how am i going to check...??

i tried the .equals method and still it wont work.

Upvotes: 0

Views: 90

Answers (4)

Elliott Frisch
Elliott Frisch

Reputation: 201477

I suggest you make it case insensitive with something like

if (optionLetter.equalsIgnoreCase("c")) {
    // ...
} else if (optionLetter.equalsIgnoreCase("f")) {
    // ...
}

or you might prefer to check the first character like

if (Character.toLowerCase(optionLetter.charAt(0)) == 'c') {
    // ...
} else if (Character.toLowerCase(optionLetter.charAt(0)) == 'f') {
    // ...
}

Upvotes: 1

Foxsly
Foxsly

Reputation: 1028

Using single quotes in Java indicates a char, while double quotes indicates a String. Switch your single quotes around c to double quotes and try using .equals().

Upvotes: 1

Matt C
Matt C

Reputation: 4555

You'll want to compare the first character in the String. It should only have one character, even so you can't compare the whole string to a char.

Your code will be:

if(optionLetter.charAt(0) == 'c') 
{
    //do stuff here
}

Comparing it to the string c will also work:

if(optionLetter.equals("c")) 
{
    //do stuff here
}

Upvotes: 2

Anubian Noob
Anubian Noob

Reputation: 13596

You could try taking the first character of the string:

if (optionLetter.charAt(0) == 'c')

Or you could compare it to the string "c" instead of the character 'c'.

if (optionLetter.equals("c"))

You can even make it case insensitive:

if (optionLetter.equalsIgnoreCase("c"))

Double quotes (") indicate String objects, while single quotes (') indicate char primitives. The String class has a method equals to compare it to other objects. To compare chars, you can just use ==.

Upvotes: 4

Related Questions