“适当地”操纵“光标”使用扫描仪读取输入文件时
这是从 .txt 输入文件中的文本行中提取字符和字符串的“正确方法”吗?
Scanner scan, readLine;
System.out.print("Enter the name of your transaction file please (include .txt extension): ");
transFilename = scan.nextLine();
scan = new Scanner(new FileReader(transFilename));
while (scan.hasNext())
{
// read a whole line, then use scanner to parse
readLine = new Scanner(scan.nextLine());
code = readLine.next().toUpperCase().charAt(0);
switch (code) {
case 'A':
lineinput = readLine.next();
filename = lineinput;
System.out.println(filename);
Scanner input = new Scanner( new FileReader(filename));
break;
}
示例输入文本文件内容如下:
A blahblah.txt
B
A gahgah.txt
当这行代码运行时: lineinput = readLine.next(); 在 while 循环迭代期间,光标是否返回到行首?我只想知道扫描仪“光标”如何穿过每一行。
例子:(^代表光标位置):
A blahblah.txt
^
Is this the "proper way" to pull a char and string from a line of text in a .txt input file?
Scanner scan, readLine;
System.out.print("Enter the name of your transaction file please (include .txt extension): ");
transFilename = scan.nextLine();
scan = new Scanner(new FileReader(transFilename));
while (scan.hasNext())
{
// read a whole line, then use scanner to parse
readLine = new Scanner(scan.nextLine());
code = readLine.next().toUpperCase().charAt(0);
switch (code) {
case 'A':
lineinput = readLine.next();
filename = lineinput;
System.out.println(filename);
Scanner input = new Scanner( new FileReader(filename));
break;
}
sample input text file reads:
A blahblah.txt
B
A gahgah.txt
When this line of code runs: lineinput = readLine.next();
Does the cursor go back to the beginning of the line during that iteration of the while loop? I just want to know how the scanner "cursor" moves through each line.
example: (^ represents the cursor position):
A blahblah.txt
^
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每次循环时,您都会从文件扫描器中获取新行,然后创建一个仅在该行上迭代的新 Scanner 实例。在
lineinput = readLine.next();
之后,光标位于'A'
行上的文件名之后;然而外部扫描仪的光标位于下一行的开头。On each pass through your loop, you fetch a new line from the file scanner and then create a new Scanner instance that iterates only over that line. After
lineinput = readLine.next();
, the cursor is after the filename on the'A'
line; however the cursor of the outer Scanner is at the beginning of the next line.