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

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

    Java provides parse methods for Primitive Types. So depending on your input you can use Integer.parseInt, Double.parseDouble or others.

    String result;
    try{
     int value = Integer.parseInt(a)+Integer.parseInt(b);
     result = String. valueOf(value) ;
    }catch(NumberFormatException ex){
     //either a or b is not a number
     result = "Invalid input";
    }
    JOptionPane.showMessageDialog(null,result);
    

提交回复
热议问题