gpt4 book ai didi

java - 可能会损失精度;从字符串中提取字符

转载 作者:行者123 更新时间:2023-11-30 05:59:49 25 4
gpt4 key购买 nike

我从用户那里获取一个字符串,然后进行一些检查以确保它有效,这是我一直在使用的代码;

char digit= userInput.charAt(0) - '0';

这一直工作得很好,直到我对另一种方法做了一些工作,我去编译并从那时起收到了“可能的精度损失”错误。

我做错了什么?

最佳答案

一方面,您应该使用 Character执行此操作的方法而不是自行开发的解决方案,即 Character.isDigit()用于检查有效性和 Character.digit()获取值:

char c = ...
if (Character.isDigit(c)) {
// it's a digit
}
int value = Character.digit(c, 10);

5.6.2 Binary Numeric Promotion 解释了您收到此警告的原因来自Java Language Specification :

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value of a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

所以发生的情况是,当您进行减法时,两个参数都被提升为 int。结果是一个int。当您尝试将 int 分配给 char 时,可能会损失精度(32 位有符号到 16 位无符号)。

另一种验证技术就是使用正则表达式:

if (s.matches("\\d\\d-\\d\\d")) {
// it's ##-##
}

或者,如果您需要获取组:

Pattern p = Pattern.compile("(\\d\\d)-(\\d\\d)");
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1)); // first group
System.out.println(m.group(1)); // second group
}

关于java - 可能会损失精度;从字符串中提取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2406362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com