将字符串转换为字节获取数字格式异常


public class HelloWorld{
public static void main(String []args){
String str = "100.00";
Short sObj2 = Short.valueOf(str);
System.out.println(sObj2);
}
}

获得以下异常:

Exception in thread "main" java.lang.NumberFormatException: For input string: "100.00"                                                                                          
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)                                                                                        
at java.lang.Integer.parseInt(Integer.java:580)                                                                                                                         
at java.lang.Short.parseShort(Short.java:118)                                                                                                                           
at java.lang.Short.valueOf(Short.java:174)                                                                                                                              
at java.lang.Short.valueOf(Short.java:200)                                                                                                                              
at HelloWorld.main(HelloWorld.java:5)   

如何解决上述问题?

首先,短短不是字节(您的问题摘要表明您正在尝试将字符串转换为字节)。Short 保存 -32,768 到 32,767(含)之间的整数值。尝试将浮点值分析为整数数据类型会导致此异常。

如果您只是想要无异常运行的代码,则以下任一方法都可以工作:

public class HelloWorld{
public static void main(String []args){
String str = "100";
Short sObj2 = Short.valueOf(str);
System.out.println(sObj2);
}
}

第一个示例通过将字符串更改为整数值来使其运行。

public class HelloWorld{
public static void main(String []args){
String str = "100.00";
Double sObj2 = Double.valueOf(str);
System.out.println(sObj2);
}
}

第二个的工作原理是将表示浮点值的字符串解析为支持浮点的变量类型。

试试这个

String str = "100";
Short sObj2 = Short.valueOf(str);

或者如果你想处理十进制值,

String str = "100.00";
Float fObj2 = Float.valueOf(str);

首先,正如您的帖子标题所暗示的那样,您希望从字符串数据类型转换为字节数据类型。这不一定包括仅显示不会生成NumberFormatException错误的值。我假设您实际上想要使用这些特定的数据类型。

为了给事情带来一个小的转折,你想从数值的字符串表示转换所有这些,该数值可以来自浮点数或双精度数据类型("100.00")。正是数字字符串中的这个小数点在进行任何转换时会给事情带来故障,因此需要在执行任何此类操作之前进行处理。

需要考虑的一些事项:

作为字符串,您可以以您喜欢的任何格式表示您喜欢的任何数字。它可以随心所欲地大,也可以随心所欲地小。我甚至可以是一个虚构或不存在的数字,但底线是......它将始终是一个字符串,您可以使用字符串数据类型执行此类操作。将 String 数值转换为实际的数字数据类型,例如字节、短整型、整数型、长整型、双精度型、浮点数等,完全是完全不同的球类游戏。有些字符串数值很容易转换,但有些则需要更具体地关注细节。

字节数据类型是 8 位有符号二进制的补码整数。它的最小值为 -128,最大值为 127(含)。

数据类型是 16 位有符号二进制的补码整数。它的最小值为 -32,768,最大值为 32,767(含)。

int(整数)数据类型是 32 位有符号二进制补码整数,其最小值为 -2147483648,最大值为 2147483647。

long数据类型是 64 位二进制补码整数。带符号长整型的最小值为 -9223372036854775808,最大值为 9223372036854775807。

最后,所有这四种数据类型都保持整数值,每种数据类型也保持值的最小值和最大值。在进行数据类型转换时,您还需要在一定程度上考虑这一点。如果要创建转换方法以从一种数据类型转换为另一种数据类型,则需要确保不超过要转换为的数据类型的最小和最大允许值。如果您想将字节数据类型转换为短数据类型或短数据类型转换为整数,这没什么大不了的,因为我们知道较小的总是在较大的中播放,但是当较大的数据类型在较小的(到字节)中播放时,情况不一定如此。

您的转换方法需要检查要转换的值,以确保它实际上适合所需的数据类型。Java 有常量来帮助你做到这一点,这样你就不必记住这些最小值和最大值,例如:Integer.MIN_VALUE和 Integer.MAX_VALUE 或Byte.MIN_VALUEByte.MAX_VALUE。

在处理数字字符串时,您可能还希望确保您正在处理的字符串实际上是数值的字符串表示形式,而不是字母数字值,例如十六进制字符串的值,或者只是一个普通的输入错误,而数字以外的字符以某种方式潜入字符串。在我看来,字符串:"100.00">是字母数字值(由于句点)和数值的字符串表示,因为它是双精度数据类型的字符串表示。它真正是什么取决于您如何处理转换方法中字符串中的句点(小数点)。

让我们再看一下该字符串值("100.00")。您可能需要考虑的另一件事是,如果我们的字符串值是:"100.74"怎么办?您希望如何处理此特定值?在将其转换为需要整数值的数据类型之前,是要向下舍入到 100 还是向上舍入到 101?

让我们将值"100.00"的字符串表示形式转换为数据类型。现在请记住,默认情况下,我在下面提供的方法将始终向下转换双精度数据类型(如果提供)的字符串表示形式,例如 100.45 或 100.99 将为 100。如果要正确向上或向下舍入这种类型的值,请在可选的roundUpDown参数中提供一个布尔值true

private short StringToShort(final String input, final boolean... roundUpDown) {
// Make sure there no dead whitespaces...
String inputValue = input.replaceAll(" ", "");
int i = 0;    // default return value is 0
// If inputValue contains nothing ("") then return 0 
if(inputValue.equals("")) { return 0; }
// Is inputValue an actual numerical value?
// Throws an exception if not.
// Handles negative and decimal point...
if (!inputValue.matches("-?\d+(\.\d+)?")) {
throw new IllegalArgumentException("nStringToShort() Method Error!n"
+ "The value supplied is not numeric (" + inputValue + ").n");
}
// Was the optional roundUpDown argument supplied?
boolean round = false;  // default is false
if (roundUpDown.length > 0) { round = roundUpDown[0]; }
// Convert the String to a Integer value
if (inputValue.contains(".")) {
// Must be a double type representation supplied
Double value = Double.parseDouble(inputValue);
if (round) { i = (int) Math.round(value); }
else { i = (int) value.intValue(); }
}
else {
// Must be a Integer type representation supplied
i = Integer.parseInt(inputValue);
}
// Is the Integer value now too small or too 
// large to be a Short data type?
if (i > Short.MAX_VALUE || i < Short.MIN_VALUE) {
throw new IllegalArgumentException("nStringToShort() Method Error!n"
+ "The value supplied is too small or too large (" + inputValue + ").n"
+ "Only values from " + Short.MIN_VALUE + " to " + Short.MAX_VALUE 
+ " are allowed!n");
}
// Finally, cast and return a short data type...
return (short) i;
}

如果您阅读代码中的所有注释,您会发现我们已经涵盖了上面讨论的所有问题。现在,根据您的帖子标题,您想转换为字节。嗯,这几乎是相同的方法,但可能做了五个左右的小更改,看看你是否能发现它们:

private byte StringToByte(final String input, final boolean... roundUpDown) {
// Make sure there no dead whitespaces...
String inputValue = input.replaceAll(" ", "");
int i = 0;    // default return value is 0
// If inputValue contains nothing ("") then return 0 
if(inputValue.equals("")) { return 0; }
// Is inputValue an actual numerical value?
// Throws an exception if not.
// Handles negative and decimal point...
if (!inputValue.matches("-?\d+(\.\d+)?")) {
throw new IllegalArgumentException("nStringToByte() Method Error!n"
+ "The value supplied is not numeric (" + inputValue + ").n");
}
// Was the optional roundUpDown argument supplied?
boolean round = false;  // default is false
if (roundUpDown.length > 0) { round = roundUpDown[0]; }
// Convert the String to a Integer value
if (inputValue.contains(".")) {
// Must be a double type representation supplied
Double value = Double.parseDouble(inputValue);
if (round) { i = (int) Math.round(value); }
else { i = (int) value.intValue(); }
}
else {
// Must be a Integer type representation supplied
i = Integer.parseInt(inputValue);
}
// Is the Integer value now too small or too 
// large to be a Byte data type?
if (i > Byte.MAX_VALUE || i < Byte.MIN_VALUE) {
throw new IllegalArgumentException("nStringToByte() Method Error!n"
+ "The value supplied is too small or too large (" + inputValue + ").n"
+ "Only values from " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE 
+ " are allowed!n");
}
// Finally, cast and return a byte data type...
return (byte) i;
}

最新更新