[英]How do I ask a user for a input file name, and then use that file name?
I am trying to ask the user for the name of their file, then I am going to scan the file to see how many indices are in the file, and then put it in an array and go from there. 我试图向用户询问其文件名,然后扫描文件以查看文件中有多少索引,然后将其放入数组中并从那里开始。
Here is my code: 这是我的代码:
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.");
}
}
I believe something went wrong with the = new File(filename);
我相信
= new File(filename);
出了点问题= new File(filename);
part: maybe because I didn't have quotes, but I'm not exactly sure. 部分:也许是因为我没有引号,但我不确定。 How can I fix this?
我怎样才能解决这个问题?
You only check if there is data in Scanner
but you never consume it. 您仅检查
Scanner
是否有数据,但从不使用它。
The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input.
java.util.Scanner.hasNext()方法如果此扫描程序的输入中包含另一个令牌,则返回true。 This method may block while waiting for input to scan.
等待输入扫描时,此方法可能会阻塞。 The scanner does not advance past any input.
扫描仪不会前进超过任何输入。
The below code will never end if there is any data in file, you increase your counter with out reading the data. 如果文件中有任何数据,则下面的代码将永无止境,您可以在不读取数据的情况下增加计数器。
while (data.hasNext()) {
indices++;
}
Change 更改
while (data.hasNext()) {
indices++;
}
to 至
while (data.hasNext()) {
indices++;
data.next();
}
You want to increment indices
for every line. 您想增加每一行的
indices
。 To achieve this, you should go to the next line and check if there are other available lines. 为此,您应该转到下一行并检查是否还有其他可用行。 Q: How can you go to the next line ?
问:您如何转到下一行? A:
data.next();
答:
data.next();
Eg - file.txt: 例如-file.txt:
Your approach - bad : 您的方法-不好 :
Step 1 第1步
line a <--- here you are line b line c
Step 2 第2步
line a <--- here you are line b line c
... ...
data.hasNext()
will be true forever because you will be on the first line at every step => infinite loop data.hasNext()
将永远为真,因为您将在每一步都位于第一行=>无限循环
Correct approach: 正确的做法:
Step 1 第1步
line a <--- here you are line b line c
Step 2 第2步
line a line b <--- here you are line c
Step 3 第三步
line a line b line c <--- here you are
In this case data.hasNext()
will return true
only 3 times, then it will return false
( the file doesn't have any line after the 3rd line ) 在这种情况下,
data.hasNext()
将仅返回true
3次,然后将返回false
(该文件在第三行之后没有任何行)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.