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

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

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

     String a= txtnum1.getText();
     String b= txtnum2.getText(); 
     JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));
    
    0 讨论(0)
  • 2020-12-07 06:09

    Since + is used to concat strings, you can't use it to add two strings containing number. But subtraction works perfectly fine with such strings. Hence, you can use this basic mathematical concept to make that possible:

    a-(-b)
    
    0 讨论(0)
  • 2020-12-07 06:10
    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);
    
    
    
    }
    

    it is work

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

    Because you want to concat Strings they won't add up. You have to parse them to an Integer which works like:

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

    To sum this up + concats Strings and doesn't add them up.

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