我可以乘以charAt在Java吗? [英] Can I multiply charAt in Java?

查看:120
本文介绍了我可以乘以charAt在Java吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试乘以charAt时,我收到了大数字:

When I try to multiply charAt I received "big" number:

String s = "25999993654";
System.out.println(s.charAt(0)+s.charAt(1));

结果:1​​03

在JAVA文档中:

the character at the specified index of this string. The first character is at index 0.

所以我需要解释或解决方案string to int,但在我看来这是不道德的工作)

So I need explanation or solution (I think that I should convert string to int , but it seems to me that is unnesessary work)

推荐答案

char 整型。在你的例子中 s.charAt(0)的值是数字50的 char 版本'2')。 s.charAt(1)(char)53 。当您在它们上使用 + 时,它们将转换为整数,最后为103(而不是100)。

char is an integral type. The value of s.charAt(0) in your example is the char version of the number 50 (the character code for '2'). s.charAt(1) is (char)53. When you use + on them, they're converted to ints, and you end up with 103 (not 100).

如果您尝试使用数字 2 5 ,你必须解析它们。或者如果你知道他们是标准的ASCII样式的数字(字符代码48到57,包括),你可以只从它们减去48(因为48是字符代码'0')。或者,如Peter Lawrey在其他地方指出,使用 Character.getNumericValue ,可处理更广泛的字符。

If you're trying to use the numbers 2 and 5, yes, you'll have to parse them. Or if you know they're standard ASCII-style digits (character codes 48 through 57, inclusive), you can just subtract 48 from them (as 48 is the character code for '0'). Or better yet, as Peter Lawrey points out elsewhere, use Character.getNumericValue, which handles a broader range of characters.

这篇关于我可以乘以charAt在Java吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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