i have this program...the color program..but i have a problem on converting a string to character. anybody can help me..thanks..

below is the java code

import javax.swing.JOptionPane;

public class ab{
    public static void main(String[]args){
    String a;       
        a=JOptionPane.showInputDialog("Enter color:  ");

// I need to convert the variable a from string to character since condition below 
//deals with a character..a is declared as a character since jOptionpane above
// accepts string.Or, do i lack some necessary header files in order to convert a 
//string to character...thanks

        if ((a=='r')||(a=='R'))
            JOptionPane.showMessageDialog(null,"RED");
        else if((a=='r')||(a=='B'))
            JOptionPane.showMessageDialog(null,"Blue");
        else
            JOptionPane.showMessageDialog(null,"Invalid Input");


    }
}

Edited 3 Years Ago by Nick Evan: Fixed formatting

The String class has a charAt() method that might be useful to you. See the String documentation in the Sun API:

http://download.oracle.com/javase/6/docs/api/java/lang/String.html

If you're not familiar with those pages, it's the place to look to find out what methods the standard classes have, and what a given method does.

While you're there, you might want to look at equals(), equalsIgnoreCase() and toUpperCase()/toLowerCase(). All of these can be useful in doing what you're trying to do - there's a couple of ways to go about it.

You can get char from a string using the charAt(int); method.

its reurn type is char

In your case you can use it as follows
char c = a.charAt(0); // this will help you in normal case.
What happens if the user give input with more than one character? :)

more than one character ... that must be invalid input

You could test the length of the String to be 1 by using one of the String methods.

You could test the length of the String to be 1 by using one of the String methods.

Could do that (while you're at the String page, find the method you'd use for that, it won't be difficult). But now we're getting into input validation - what do you do if they do give you bad input? Right now you just tell them it was bad. What about giving them a chance to try again?

Right. Speaking of strings, don't forget to tie one to the post on the way in, so you can find your way back out again. If you get lost in there, just holler.

This question has already been answered. Start a new discussion instead.