2017-05-06 25 views
0

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

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

它从输入字段(文本框)的值,把它添加到ListLeft,然后也增加oList和当我运行该程序时,它应该输出十进制或相同的文字在ListLeft 。

here is how it looks like

+1

使用['Integer.parseInt'](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html# parseInt-java.lang.String-int-)与适当的基数。如果失败了,那么它不是二元的。 –

回答

1

首先检查如果String 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; 
+0

谢谢!!!现在我只需要做到这样,即使用户添加了4个输入,程序也输出了全部四个输入,而不是最后一个输出。 –

+0

你需要自己做! –

+1

是的,再次感谢你! –

0

试试这个

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