在此代碼片段,我不能總結a
和b
:如何找到兩個數字在字符串變量中的總和?
String a = "10";
String b = "20";
JOptionPane.showMessageDialog(null,a+b);
由於a
和b
被定義爲String
,這個代碼將串聯的串和輸出10+20=1020
。
我怎樣才能得到它,而不是總和a
和b
和輸出10+20=30
?
在此代碼片段,我不能總結a
和b
:如何找到兩個數字在字符串變量中的總和?
String a = "10";
String b = "20";
JOptionPane.showMessageDialog(null,a+b);
由於a
和b
被定義爲String
,這個代碼將串聯的串和輸出10+20=1020
。
我怎樣才能得到它,而不是總和a
和b
和輸出10+20=30
?
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);
嘗試:Integer.parseInt(a)+Integer.parseInt(b)
String a= txtnum1.getText();
String b= txtnum2.getText();
JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));
我必須使用'。獲取'調用a和b的代碼,所以它不起作用。 – celikgumusdag 2011-04-08 10:08:33
@ÇelikGümüşdağ:你在哪裏使用'.get'?爲什麼這不起作用? – 2011-04-08 10:13:40
現在是工作。感謝您的編輯。 – celikgumusdag 2011-04-08 10:17:10
因爲你想concat字符串他們不會加起來。您必須將它們解析爲Integer,其格式如下:
Integer.parseInt(a) + Integer.parseInt(b)
總結了+ concats字符串,並不加上它們。
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);
}
是工作
整數包裝類具有構造函數接受表示數字的字符串參數。
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";
}
我們可以改變字符串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));
}
}
使用BigInteger類在很大程度上執行字符串添加操作。
BigInteger big = new BigInteger("77777777777777777777888888888888888888888888888856666666666666666666666666666666");
BigInteger big1 = new BigInteger("99999999999999995455555555555555556");
BigInteger big3 = big.add(big1);
我必須定義a和b int – celikgumusdag 2011-04-08 10:04:20