如何找到String变量中两个数字的总和? [英] How can I find the sum of two numbers which are in String variables?

查看:128
本文介绍了如何找到String变量中两个数字的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码片段中,我无法求和 a b

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

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

由于 a b 定义为 String ,此代码将连接字符串并输出 10 + 20 = 1020

Since a and b are defined as String, this code will concatenate the strings and output 10+20=1020.

我怎样才能得到它而不是 a b 并输出 10 + 20 = 30

How can I get it to instead sum a and b and output 10+20=30?

推荐答案

Java为Primitive Types提供了解析方法。因此,根据您的输入,您可以使用Integer.parseInt,Double.parseDouble或其他。

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 = ""+value;
}catch(NumberFormatException ex){
 //either a or b is not a number
 result = "Invalid input";
}
JOptionPane.showMessageDialog(null,result);

这篇关于如何找到String变量中两个数字的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆