【发布时间】:2014-02-08 16:36:42
【问题描述】:
如果有人能指出我正确的方向,我将不胜感激。我正在使用 Scanner 类读取文本文件。在数据文件的末尾,我有一个“EOF”预告片。我希望 while 循环在遇到“EOF”时立即停止。我的想法是将“&&”语句放在while循环中,但会引发运行时错误。
数据.txt
January Feburary March
January Feburary March
January Feburary March
January Feburary March
January Feburary March
EOF EOF EOF
代码:
public class ReadFile {
static Scanner input;
static final int MAX_LEN = 50;
static int counter = 0;
static String filePath = "data.txt";
static File file;
static Records[] records;
//METHOD: MAIN
public static void main(String[] args){
records = new Records[ MAX_LEN ];
try {
file = new File( filePath );
input = new Scanner( file );
do{
records[counter] = new Records();
records[counter].str1 = input.next();
records[counter].str2 = input.next();
records[counter].str3 = input.next();
++counter;
}
while(input.hasNextLine() && records[conter-1].str1 != "EOF");
input.close();
}
catch ( IOException ex ){
System.out.println( "File access error" );
counter = 0;
}//
}//MAIN
【问题讨论】:
-
只要说当行等于行尾
EOF就可以通过使用break中断循环来停止循环。