Java 空行不存储为null,而循环不会终止
在我的程序中,我从我放在下面的一个.dat文件中读取数据,我希望while循环在到达空白行时停止。在我的代码中,我将其设置为当单词[0]等于null时,它将停止。但这并没有发生,我最终得到了一个错误。当我将其更改为文字[0]!=空或!=”“这两个似乎都不管用 DAT 节目Java 空行不存储为null,而循环不会终止,java,Java,在我的程序中,我从我放在下面的一个.dat文件中读取数据,我希望while循环在到达空白行时停止。在我的代码中,我将其设置为当单词[0]等于null时,它将停止。但这并没有发生,我最终得到了一个错误。当我将其更改为文字[0]!=空或!=”“这两个似乎都不管用 DAT 节目 import java.util.*; import java.io.*; public class matrix{ public static void main(String[] args){ int[][] arra
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
到达空位线时停止。在我的代码中,我将其设置为当单词[0]等于null时,它将停止
如果到达流的末尾,A将只返回null
。要检查空行,请检查返回字符串的长度-如果长度为0,则表示已到达空行(您也可以选择修剪该行,以确保在计算长度时忽略前导和尾随空格)
好的,我可以解释一下您所说的流结束是什么意思,以供将来参考。在阅读文件的上下文中,
流结束
表示文件结束。
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
String line = br.readLine();
if(line.trim().length() != 0){
//line is not empty
}
try
{
BufferedReader br = new BufferedReader(new FileReader(new File("p8.dat")));
while (true)
{
String line = br.readLine();
if (line == null)
{
// end of file! then exit the loop
break;
}
if (line.trim().length() == 0)
{
// the line is empty! then goto next line
continue;
}
String[] words = line.split(" ");
int num=Integer.parseInt(words[0]);
int numTwo=Integer.parseInt(words[1]);
System.out.println(num+" "+numTwo);
}
}