1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java JOptionPane and accepting characters as input

  1. Oct 20, 2011 #1
    I am writing a program using JOptionPane that asks the user to input a decimal number, and then outputs the decimal number in binary. The program then asks the user if they would like to convert another decimal to enter y/n (with case being irrelevant). I was able to ask the user for the decimal and do the conversion and output the binary answer, however I do not know how to deal with the user entering characters in the JOptionPane box. I want to use something like char answer = Character.parseChar();, but all of my googling and researching has told me that this does not exist. If you could lead me in the right direction that would be great! I've been stuck on this small detail for way too long.

    My code is below:

    package p032;

    import javax.swing.JFrame;
    import javax.swing.JOptionPane;

    public class P032 {



    public static void main(String[] args) {

    String decimalToConvertString =
    JOptionPane.showInputDialog("Enter decimal to convert");
    int decimalToConvert = Integer.parseInt(decimalToConvertString);



    String binaryNumberString = "";


    while (decimalToConvert != 0){
    int remainder = decimalToConvert % 2;
    String remainderString = String.valueOf(remainder);
    binaryNumberString = remainderString + binaryNumberString;
    decimalToConvert = (decimalToConvert - remainder) / 2;
    }

    JOptionPane.showMessageDialog(null, "Binary number: " + binaryNumberString);


    String answerString = JOptionPane.showInputDialog("Convert another (y/n)?");
     
  2. jcsd
  3. Oct 21, 2011 #2

    Mark44

    Staff: Mentor

    When you post code for us to look at, put a [ code ] tag at the beginning and a [ /code ] tag at the end (but without the extra spaces. Doing so preserves your indentation and makes the code easier to read. I have done this for your example.
    First off, you're missing two closing braces at the end.
     
  4. Oct 21, 2011 #3

    Mark44

    Staff: Mentor

    Since you are converting base-10 numbers, the user should not be entering characters. If this is something you need to guard against, read the user's input as a string, and then convert the string to an int. Here's a link to some code that is similar: http://download.oracle.com/javase/tutorial/java/data/converting.html
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java JOptionPane and accepting characters as input
Loading...