空行不存储为null,而循环不会终止

时间:2015-05-05 19:07:27

标签: java

在我的程序中,我从下面的.dat文件中读取,我希望while循环在到达空白行时停止。在我的代码中,我将它设置为当单词[0]等于null时它将停止。但这并没有发生,我最终得到一个错误。当我把它改为单词[0]!= null或!=" "似乎都不起作用。

DAT

1 2
1 3
2 2
2 3
2 6
3 4
3 5
4 1
4 4
4 5
5 5
5 6
5 7
5 9
6 1
6 8
7 7
7 8    
7 9
8 8
8 10
9 8
9 10
10 10
10 4

1 10 10
1 5 2
2 4 7
3 9 4
3 10 1
3 4 3
5 8 2
9 10 1
7 10 4
6 9 3
2 9 5
4 8 2

PROGRAM

import java.util.*;
import java.io.*;

public class matrix{

public static void main(String[] args){
int[][] arrayNums = new int[9][9];
String[] words = new String[10];

// Location of file to read
    File file = new File("p8.dat");

 try {           
     BufferedReader br = new BufferedReader(new FileReader(new File("p8.dat")));

     words[0]="-1";//TO initiate while loop    
     while(words[0] != null){   
    words=br.readLine().split(" ");

        if(words[0]!= null){


            int num=Integer.parseInt(words[0]);
            int numTwo=Integer.parseInt(words[1]);

            System.out.println(num+" "+numTwo);
}//END IF



}//END WHILE


    }//END TRY---------------------------------------------------------

catch(Exception e){
    System.err.println("Error: Target File Cannot Be Read");
}

}//end main-----------------------------------------------------------
}//end class

输出

1 2
1 3
2 2
2 3
2 6
3 4
3 5
4 1
4 4
4 5
5 5
5 6
5 7
5 9
6 1
6 8
7 7
7 8
7 9
8 8
8 10
9 8
9 10
10 10
10 4
Error: Target File Cannot Be Read

2 个答案:

答案 0 :(得分:2)

  

当它到达空白行时停止。在我的代码中,我将它设置为当单词[0]等于null时它将停止

如果到达流的末尾,则BufferedReader只会返回null。要检查空行,检查返回的字符串的长度 - 如果长度为0,那么您已到达空行(您也可以选择修剪该行以确保在计算长度时省略前导和尾随空格)< / p>

String line = br.readLine();

if(line.trim().length() != 0){
    //line is not empty
}

答案 1 :(得分:0)

String option = request.getParameterName("recordLimit") // get option selected
session.setAttrubute("recordLimit", option) // display last option selected from session
相关问题