如果输入仅包含 1 和 0,则将其从二进制转换为十进制

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

我正在写一个程序,它由两个列表组成——左边是输入列表,右边是输出列表。它要求用户输入任何文本或数字,然后将输入添加到左侧的列表中。如果用户输入仅包含 1 和 0,当程序为 运行 时,它将输入从二进制转换为十进制。例如,如果用户输入“111001 a”或“112”——它根本不会改变。我只是在为这部分的代码苦苦挣扎。我保证我应该在那里使用,但你能帮忙吗?

 /*
    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++;
}

它从输入字段 (textField) 获取值,将其添加到 ListLeft,然后也添加到 oList,当我 运行 程序时,它应该输出十进制或与在 ListLeft.

here is how it looks like

首先检查字符串 value 是否包含除 10 之外的字符,如果不包含则将其更改为 decimal 值。

String value = textField.getText();
String result;
String str = value.replaceAll("[01]","");

if(str.isEmpty())
    result=Integer.toString(Integer.parseInt(value,2));
else
    result=value;

试试这个

String s = "1010a";
try{
    int i = Integer.parseInt(s, 2);
    //Do something(no is valid)
}catch(NumberFormatException e){
    //Display error(no is invalid)
}