如何将两个字符串转换为整数以使数学正确?
我想要结果 no:5 但我得到 no:23
public class Assignment3
{
public static void main(String args[])
{
String str1 = "2";
String str2 = "3";
System.out.println("Result:" + (str1+str2) );
}
}
I want the result no:5 but I get no:23
public class Assignment3
{
public static void main(String args[])
{
String str1 = "2";
String str2 = "3";
System.out.println("Result:" + (str1+str2) );
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您希望对整数进行算术运算,则需要告诉代码解析这些值。目前它仅使用字符串连接运算符,因为两个操作数(
str1
和str2
)都是字符串表达式。尝试一下:
请注意,当您使用“真实”数据(而不是此处肯定有效的硬编码值)时,
Integer.parseInt
将抛出NumberFormatException
如果你给它类似“x”的东西而不是数字。If you want arithmetic to be done on integers, you need to tell your code to parse the values. Currently it's just using the string concatenation operator, because both of the operands (
str1
andstr2
) are string expressions.Try this:
Note that when you're using "real" data (instead of hard-coded values which will definitely be valid here),
Integer.parseInt
will throw aNumberFormatException
if you give it something like "x" instead of a number.str1
和str2
是String
对象。+
运算是为String
对象定义的,其工作方式类似于这些字符串的串联:如果您需要算术
+
运算,那么您需要数字类型(int、float、...)。在这种情况下,您必须将字符串解析为数值,例如:str1
andstr2
areString
objects. The+
operation is defined forString
objects and works like a concatenation of those Strings:If you need an arithmetic
+
operation, then you need numeric types (int, float, ...). In you're case, you'll have to parse the Strings to numeric values, like:整数.parseInt(String string);
Integer.parseInt(String string);
您需要使用
parseInt()
。 Java 中使用“+”运算符连接两个字符串以及添加两个数字。因此,您必须将字符串转换为整数才能使用“+”运算符将它们相加。编辑:
还有
parseFloat()
和parseDouble()
如果您使用的是十进制数字You need to use
parseInt()
. The "+" operator is used in Java to concatenate two strings as well as to add two numbers. So you have to convert the strings to an integer to be able to add them with the "+" operator.EDIT:
There is also
parseFloat()
andparseDouble()
if you are working with decimal numbers这个怎么样?
How about this?
您将数字字符串视为文本字符串,但实际上您需要将字符串解析为整数。
You are treating numerical strings as textual strings, but actually you need to parse the strings to Integer.