2016-11-17 85 views
0

我一直在分裂语句得到一个空指针异常。我已经初始化了all_data1变量,当使用split时,它必须是一个数组。 请建议我在做什么错... 这是供大家参考代码...空指针异常时使用拆分

test_cases = t_inp.nextInt();  //input test cases 
    for(i=0;i<test_cases;i++) 
    { 
     String all_data = ""; 
     all_data = d_inp.readLine(); 
     all_data1 = all_data.split("\\s+"); 
     up_bnd[i] = Integer.parseInt(all_data1[i]); 
     lw_bnd[i] = Integer.parseInt(all_data1[i+1]); 
     Arrays.fill(all_data1, ""); 
     System.out.println(up_bnd); 
     System.out.println(lw_bnd); 

    }   
+1

'all_data'的值是什么? –

+0

您必须更具体地了解'all_data'的具体内容,您可能会遇到异常情况,因为'.readLine()'没有捕获任何输入,因此没有任何可分割的内容。 – px06

+0

首先将all_data初始化为“”(空字符),然后使用readLine()和split ...有可能没有行被d_inp读取,并且all_data变为null并导致异常 – Sajad

回答

3

这取决于你从输入读数得到什么。

我推测你使用BufferedReader,它有readLine

的Javadoc指出:

/** 
    * Reads a line of text. A line is considered to be terminated by any one 
    * of a line feed ('\n'), a carriage return ('\r'), or a carriage return 
    * followed immediately by a linefeed. 
    * 
    * @return  A String containing the contents of the line, not including 
    *    any line-termination characters, or null if the end of the 
    *    stream has been reached 
    * 
    * @exception IOException If an I/O error occurs 
    * 
    * @see java.nio.file.Files#readAllLines 
    */ 
    public String readLine() throws IOException { 
     return readLine(false); 
    } 

因此,无论你得到一个EOL字符或您的流已经达到了他的结局。

如果从输入中得到新的行,那么您可以使用readLine(boolean ignoreLF),这将忽略EOL字符。