Search code examples
javaswinglistuser-interfacejavabeans

If input consists of ONLY 1s and 0s, convert it from binary to decimal


I'm writing a program, which consists of two lists - on the left is input list and on the right is output list. It asks for user to input any text or numbers and then adds the input to the list on the left. IF the user input consists of only 1 and 0, when the program is run, it converts the input from binary to decimal. If the user inputs, for example, "111001 a" or "112" - it doesn't get changed at all. I am struggling with the code for this part only.. I assuse I am supposed to use while in there, but can you help?

 /*
    private String oList[];
    private JList<String> ListRight;
    addCounter = 0;
    oList = new String[10];  */


void run() {

    String value = textField.getText();
    String result =

    //while input consists of ONLY 1s and 0s, convert from binary to decimal

    oList[addCounter] = result;

    ListRight.setListData(oList);
    outCounter++;
}

It takes the value from input field (textField) , adds it to the ListLeft, then also adds to oList and when I run the program, it is supposed to output either decimal or the same text as in ListLeft.

here is how it looks like


Solution

  • Check first if the String value contains characters excepts 1 and 0 and If it doesn't contain then change it to the decimal value.

    String value = textField.getText();
    String result;
    String str = value.replaceAll("[01]","");
    
    if(str.isEmpty())
        result=Integer.toString(Integer.parseInt(value,2));
    else
        result=value;