How can I find the sum of two numbers which are in String variables?

后端 未结 9 1379
孤独总比滥情好
孤独总比滥情好 2020-12-07 05:36

In this code fragment, I can\'t sum a and b:

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


        
9条回答
  •  孤街浪徒
    2020-12-07 06:18

    We can change string to BigInteger and then sum its values.

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

提交回复
热议问题