2013-10-26 18 views
1

此代碼適用於某些輸入。 但我得到一個NumberFormatError爲更高的輸入值,如1000000. 輸入(採取s [])範圍從值1-2000000 可能是什麼原因?大型輸入的數字格式例外

import java.io.*; 
import java.util.*; 
import java.text.*; 
import java.math.*; 
import java.util.regex.*; 

public class Solution { 

    public static void main(String[] args) { 
     /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 

     try 
     { 
     BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 

     int no=Integer.parseInt(read.readLine()); 

     String s[]=read.readLine().split(" "); 

     int result=0; 

     for(int i=0; i<no; i++) 
     { 
      result+= Integer.parseInt(s[i]); 
      if(result<0) 
       result=0; 
     } 
     System.out.println(result); 

     } 
     catch(IOException e) 
     { 
      System.out.println(e.getMessage()); 
     } 
    } 
} 
+3

你可以給你輸入例外嗎?! – SudoRahul

+0

你可以發佈異常的堆棧跟蹤嗎? – Evans

+0

有沒有答案可以回答你的問題?如果是這樣,請將您最喜歡的答案標記爲已解決,如果不是,請提供更多信息。 – Izmaki

回答

3

在for循環中,您輸入的第一位數字是數組的大小。這就是你的邏輯到目前爲止。除非你實際上手動加載了2,000,000個數字(或複製/粘貼),否則會拋出一個ArrayIndexOutOfBoundsException

你會得到一個NumberFormatException如果你是在作爲第二輸入,或將大於Integer.MAX_VALUE(2147483647)或小於Integer.MIN_VALUE(-2147483648)輸入非數字字符。

輸入類似:

1000000 
2 1 2 1 2 1 /*... 999990 digits later ...*/ 2 1 2 1 

使程序正確終止。這裏是我使用的輸入文件,如果有人想要它:http://ge.tt/95Lr2Kw/v/0

該程序是編譯和手動從一個命令promt像這樣:java Solution < in.txt

編輯:我只記得數組中的輸入值可能大到2000000.您將不得不使用BigInteger來保存result值大到2000000^2。

0

我同意@lzmaki。 我沒有爲您的值獲取任何NumberFormatException。 但是,我得到這實際上從計算器造成當我試圖這樣ArrayIndexOutofBoundException:

1000000 
1 2 3 
then enter 

在那個時候,系統識別出它具有數據保持這樣龐大的數字在它的堆棧內存不夠。

我NumberFormatException的下列情況:

1000000 
enter twice 

監守沒有系統得到一個非數字格式轉換成整數格式,這是「」。

我希望我的分析,幫助你找到你的錯誤:)

0

假設它不是一個緩衝區溢出,傳遞給Integer.parseInt任何非數字字符將引發NumberFormatException。這包括空格和不可打印的字符,如換行符和小數點(因爲浮點數不是整數)。

當您撥打read.readLine()時,您可以嘗試使用.trim()驗證您的輸入,並在傳遞到Integer.parseInt()之前檢查空串或空串。例如:

 String input = read.readLine(); 

    if (input != null) 
     input = input.trim(); 
    if (input.equals("")) 
     throw new IllegalArgumentException("Input must be a number"); 

    int no=Integer.parseInt(input); 

但是,您決定驗證第一行的輸入,對第二個readLine()調用也做。希望你可以精確地縮小導致問題的原因。