我试图向用户询问文件的名称,然后扫描文件以查看文件中有多少索引,然后将其放入数组中并从那里开始。
这是我的代码:
import java.util.*;
import java.io.*;
public class TestScoresAndSummaryStatistics {
public static void main(String[] args) throws IOException {
int scores;
int indices = -1;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of the file");
String fileName = keyboard.next();
//I believe something is wrong here, am I incorrectly bring inputFile into new File?
File inputFile = new File(fileName);
Scanner data = new Scanner(inputFile);
while (data.hasNext()) {
indices++;
}
System.out.println("There are: " + indices + "indices.");
}
}
我认为该= new File(filename);
零件出了点问题:也许是因为我没有引号,但我不确定。我怎样才能解决这个问题?
改变
while (data.hasNext()) {
indices++;
}
到
while (data.hasNext()) {
indices++;
data.next();
}
您想indices
为每一行增加。为此,您应该转到下一行并检查是否还有其他可用行。问:您如何转到下一行?A: data.next();
例如-file.txt:
您的方法-不好:
步骤1
line a <--- here you are
line b
line c
第2步
line a <--- here you are
line b
line c
...
data.hasNext()
永远是对的,因为您将在每一步都走在第一行=>无限循环
正确的做法:
步骤1
line a <--- here you are
line b
line c
第2步
line a
line b <--- here you are
line c
第三步
line a
line b
line c <--- here you are
在这种情况下,data.hasNext()
将true
仅返回3次,然后它将返回false
(文件在第三行之后没有任何行)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句