如何找到String变量中两个数字的总和?

在这段代码中,我不能总结ab

 String a = "10"; String b = "20"; JOptionPane.showMessageDialog(null,a+b); 

由于ab被定义为String ,因此该代码将连接字符串并输出10+20=1020

如何得到它而不是总和ab并输出10+20=30

Java为Primitive Types提供了解析方法。 因此,根据您的输入,您可以使用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,其工作方式如下:

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

总结这个+ concats字符串,并没有添加它们。

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

  String a= txtnum1.getText(); String b= txtnum2.getText(); JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b)); 
 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参数。

 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);