[英]How do I ask a user for a input file name, and then use that file name?
我试图向用户询问其文件名,然后扫描文件以查看文件中有多少索引,然后将其放入数组中并从那里开始。
这是我的代码:
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);
出了点问题= new File(filename);
部分:也许是因为我没有引号,但我不确定。 我怎样才能解决这个问题?
您仅检查Scanner
是否有数据,但从不使用它。
java.util.Scanner.hasNext()方法如果此扫描程序的输入中包含另一个令牌,则返回true。 等待输入扫描时,此方法可能会阻塞。 扫描仪不会前进超过任何输入。
如果文件中有任何数据,则下面的代码将永无止境,您可以在不读取数据的情况下增加计数器。
while (data.hasNext()) {
indices++;
}
更改
while (data.hasNext()) {
indices++;
}
至
while (data.hasNext()) {
indices++;
data.next();
}
您想增加每一行的indices
。 为此,您应该转到下一行并检查是否还有其他可用行。 问:您如何转到下一行? 答: 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
(该文件在第三行之后没有任何行)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.