2011-04-08 39 views

回答

5

Java提供基本類型的解析方法。因此,根據您的輸入,您可以使用Integer.parseInt,Double.parseDouble或其他。

String result = ""; 
try{ 
int value = Integer.parseInt(a)+Integer.parseInt(b); 
result = ""+value; 
}catch(NumberFormatException ex){ 
//either a or b is not a number 
result = "Invalid input"; 
} 
JOptionPane.showMessageDialog(null,result); 
1

嘗試:Integer.parseInt(a)+Integer.parseInt(b)

String a= txtnum1.getText(); 
String b= txtnum2.getText(); 
JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b)); 
+0

我必須使用'。獲取'調用a和b的代碼,所以它不起作用。 – celikgumusdag 2011-04-08 10:08:33

+0

@ÇelikGümüşdağ:你在哪裏使用'.get'?爲什麼這不起作用? – 2011-04-08 10:13:40

+0

現在是工作。感謝您的編輯。 – celikgumusdag 2011-04-08 10:17:10

2

因爲你想concat字符串他們不會加起來。您必須將它們解析爲Integer,其格式如下:

Integer.parseInt(a) + Integer.parseInt(b) 

總結了+ concats字符串,並不加上它們。

0
public void actionPerformed(ActionEvent arg0) 
{ 
    String a= txtnum1.getText(); 
    String b= txtnum2.getText(); 
    String result = ""; 
    try{ 
    int value = Integer.parseInt(a)+Integer.parseInt(b); 
    result = ""+value; 
    }catch(NumberFormatException ex){ 

    result = "Invalid input"; 
    } 
    JOptionPane.showMessageDialog(null,result); 



} 

是工作

0

整數包裝類具有構造函數接受表示數字的字符串參數。

String a= txtnum1.getText();//a="100" 
String b= txtnum2.getText();//b="200" 

Integer result; 
int result_1; 
String result_2; 

try{ 
result = new Integer(a) + new Integer(b); // here variables a and b are Strings representing numbers. If not numbers, then new Integer(String) will throw number format exception. 

int result_1=result.intValue();//convert to primitive datatype int if required. 

result_2 = ""+result; //or result_2 = ""+result_1; both will work to convert in String format

}catch(NumberFormatException ex){ 
//if either a or b are Strings not representing numbers 
result_2 = "Invalid input"; 
} 
0

我們可以改變字符串BigInteger和再總結自己的價值觀。

import java.util.*; 
import java.math.*; 
class stack 
{ 
    public static void main(String args[]) 
    { 
     Scanner s=new Scanner(System.in); 
     String aa=s.next(); 
     String bb=s.next(); 
     BigInteger a=new BigInteger(aa); 
     BigInteger b=new BigInteger(bb); 
     System.out.println(a.add(b)); 
    } 
} 
0

使用BigInteger類在很大程度上執行字符串添加操作。

BigInteger big = new BigInteger("77777777777777777777888888888888888888888888888856666666666666666666666666666666"); 
     BigInteger big1 = new BigInteger("99999999999999995455555555555555556"); 
     BigInteger big3 = big.add(big1); 
相關問題