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

后端 未结 9 1370
孤独总比滥情好
孤独总比滥情好 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: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";
    }
    

提交回复
热议问题