【问题标题】:If input consists of ONLY 1s and 0s, convert it from binary to decimal如果输入仅由 1 和 0 组成,则将其从二进制转换为十进制
【发布时间】:2017-05-06 10:54:55
【问题描述】:

我正在编写一个程序,它由两个列表组成——左边是输入列表,右边是输出列表。它要求用户输入任何文本或数字,然后将输入添加到左侧的列表中。如果用户输入仅由 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

【问题讨论】:

  • 使用带有适当基数的Integer.parseInt。如果它失败了,那么它就不是二进制的。

标签: java swing list user-interface javabeans


【解决方案1】:

首先检查字符串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;

【讨论】:

  • 谢谢!!!现在我只需要让它即使用户添加了 4 个输入,程序也会输出所有四个,而不仅仅是最后一个。
  • 你需要自己做的!
【解决方案2】:

试试这个

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

【讨论】:

    猜你喜欢
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2017-01-03
    • 2017-03-03
    • 2019-06-10
    • 2021-12-30
    相关资源
    最近更新 更多