2013-05-27 80 views
0

您好我想知道如何使用一個名爲s的字符串,將它分成兩個單獨的字符串,將字符串轉換爲整數,然後將兩個字符串相加。分割一個字符串,然後將兩個字符串加在一起

public String add() throws IOException { 

    int answer; 

    String s = input; 

    String[] strings = s.split(" + "); 
    String string1 = strings[0].trim(); 
    String string2 = strings[1].trim(); 

    int x = Integer.parseInt(string1); 
    int y = Integer.parseInt(string2); 

    answer = x + y; 
    System.out.println(answer); 
    return "" + answer; 
} 
+9

這裏有什麼問題嗎? –

+0

要從命令行讀取,請使用: Scanner in = new Scanner(System.in); input = in.nextLine() –

回答

4

嘗試這種模式

String[] strings = s.split("\\+"); 
2

添加input變量作爲函數參數

public String add(String input) throws IOException { 

然後代替字符串S = input`;

使用

String[] strings = input.split(" + "); 

然後調用

add("3 + 2"); 
相關問題