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

后端 未结 9 1260
孤独总比滥情好
孤独总比滥情好 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:22

    use BigInteger class to perform largely in length string addition operation.

    BigInteger big = new BigInteger("77777777777777777777888888888888888888888888888856666666666666666666666666666666");
            BigInteger big1 = new BigInteger("99999999999999995455555555555555556");
            BigInteger big3 =   big.add(big1);
    
    0 讨论(0)
  • Integer.parseInt() is used to convert String to Integer.In order to perform sum of two strings first strings need to be converted to Integers and then need to perform sum otherwise it just concatenates two strings instead of performing sum.

    String a = "10"; String b = "20";

    JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));

    0 讨论(0)
  • 2020-12-07 06:29

    Integer wrapper class has constructor which takes String parameter representing numbers.

    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 讨论(0)
提交回复
热议问题