2017-05-06 79 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) 
} 
相關問題