如何避免JAVA中的NumberFormatException?
我正在尝试连接数组的所有元素。所以我写了这段代码。但这给了NumberFormatException如何避免JAVA中的NumberFormatException?,java,arrays,numberformatexception,Java,Arrays,Numberformatexception,我正在尝试连接数组的所有元素。所以我写了这段代码。但这给了NumberFormatException BigInteger sum = BigInteger.ZERO; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); int arr[] = new int[n];
BigInteger sum = BigInteger.ZERO;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int arr[] = new int[n];
for(int i=0; i<n; i++){
arr[i] = Integer.parseInt(reader.readLine());
sum = sum.multiply(BigInteger.TEN);
sum = sum.add(BigInteger.valueOf(arr[i]));
}
示例:假设数组元素为1 5 7 5 6 7 5。然后连接的数字将是1575675。n是数组元素的数目。这里,BigInteger用于非常大的n值。请帮助我避免这个问题。当试图帮助某人时,这会让人非常沮丧。您没有向我们展示您的实际输入,因此很难猜测您真正在做什么。请解释您的输入与下面的不同之处。使用下面的模板向我们展示您的输入内容
public static void main( String[] args )
throws Exception
{
BigInteger sum = BigInteger.ZERO;
//BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
StringReader testVectors = new StringReader( "4\n1\n2\n3\n0\n" );
BufferedReader reader = new BufferedReader( testVectors );
int n = Integer.parseInt( reader.readLine() );
int arr[] = new int[ n ];
for( int i = 0; i < n; i++ ) {
arr[i] = Integer.parseInt( reader.readLine() );
sum = sum.multiply( BigInteger.TEN );
sum = sum.add( BigInteger.valueOf( arr[i] ) );
System.out.println( "sum=" + sum );
}
}
上面这一行就是问题所在,因为您正在声明输入是正确的
1 5 7 5 6 7 5 // Space delimited numbers passed as the command line arguments
reader.readLine(); // This reads the entire line into String
因此,现在您将整个输入存储到一个以空格作为分隔符的字符串中,但是如果您尝试解析以空格分隔的字符串,您将得到NumberFormatException
为了避免这种情况,你可以这样做
String [] inputs = reader.readLine().split(" "); // Splitting the input with space
for(String s: inputs) {
int value = Integer.parseInt(s); //Now it will parse correctly.
}
1575675不是15775的和。你的原始数据是什么样子的?尝试将字符串1 5 7 5 6 7 5读入整数会导致异常,这一点也不奇怪。是的,有准确的输入在这里会有所帮助。如果这是你的字符串,那么它显然不起作用。或者它是157?请仔细阅读。我已经写了,我正在尝试连接数组的所有元素。sum只是一个变量,根据我在下面给出的输入,他的程序实际运行。同样地,如果没有准确的输入,我们无法判断出什么是错误的。是的,但是因为他的程序失败了,所以输入可能与你给出的不一样。
1 5 7 5 6 7 5 // Space delimited numbers passed as the command line arguments
reader.readLine(); // This reads the entire line into String
String [] inputs = reader.readLine().split(" "); // Splitting the input with space
for(String s: inputs) {
int value = Integer.parseInt(s); //Now it will parse correctly.
}