【问题标题】:Using scanner with a prompt and user input使用带有提示和用户输入的扫描仪
【发布时间】:2013-08-17 11:55:21
【问题描述】:

我尝试从用户“输入”文件中计算行数、单词数、字符数。
在这个节目数完之后,再继续询问。

如果文件不存在,则打印运行期间统计的所有数据。

代码:

public class KeepAskingApp {
    private static int lines;
    private static int words;
    private static int chars;

public static void main(String[] args) {
    boolean done = false;
    //counters
    int charsCount = 0, wordsCount = 0, linesCount = 0;
    Scanner in = null;  
    Scanner scanner = null;
    while (!done) {
        try {
            in = new Scanner(System.in);
            System.out.print("Enter a (next) file name: ");
            String input = in.nextLine();

            scanner = new Scanner(new File(input));     
            while(scanner.hasNextLine()) {
                lines += linesCount++;
                Scanner lineScanner = new Scanner(scanner.nextLine());
                lineScanner.useDelimiter(" ");
                while(lineScanner.hasNext()) {
                    words += wordsCount++;
                    chars += charsCount += lineScanner.next().length();
                }
                System.out.printf("# of chars: %d\n# of words: %d\n# of lines: ", 
                        charsCount, wordsCount, charsCount);

                lineScanner.close();
            }

            scanner.close();
            in.close();
        } catch (FileNotFoundException e) {
            System.out.printf("All lines: %d\nAll words: %d\nAll chars: %d\n", 
                    lines, words, chars);
            System.out.println("The end");
            done = true;
        } 
    }
}

}

但我不明白为什么它总是显示没有参数的输出:

All lines: 0
All words: 0
All chars: 0
The end

为什么它省略了所有内部部分。
可能是因为我使用的扫描仪很少,但看起来一切正常。 有什么建议吗?

更新:

感谢所有提供一些提示的人。我用新的信息重新思考所有构造和重写的代码。
为了避免棘手的扫描仪输入行,我使用了JFileChooser:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;

public class KeepAskingApp {
    private static int lines;
    private static int words;
    private static int chars;

    public static void main(String[] args) {
        boolean done = false;
        // counters
        int charsCount = 0, wordsCount = 0, linesCount = 0;
        Scanner in = null;
        Scanner lineScanner = null;
        File selectedFile = null;
        while (!done) {
            try {
                try {
                    JFileChooser chooser = new JFileChooser();

                    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                        selectedFile = chooser.getSelectedFile();
                        in = new Scanner(selectedFile);
                    }
                    while (in.hasNextLine()) {
                        linesCount++;
                        lineScanner = new Scanner(in.nextLine());
                        lineScanner.useDelimiter(" ");
                        while (lineScanner.hasNext()) {
                            wordsCount++;
                            charsCount += lineScanner.next().length();
                        }

                    }
                    System.out.printf(
                            "# of chars: %d\n# of words: %d\n# of lines: %d\n",
                            charsCount, wordsCount, linesCount);

                    lineScanner.close();
                    lines += linesCount;
                    words += wordsCount;
                    chars += charsCount;

                    in.close();
                } finally {
                    System.out.printf(
                            "\nAll lines: %d\nAll words: %d\nAll chars: %d\n",
                            lines, words, chars);
                    System.out.println("The end");
                    done = true;
                }
            } catch (FileNotFoundException e) {
                System.out.println("Error! File not found.");
            }
        }
    }
}

【问题讨论】:

  • 这是一个糟糕的代码,原因有很多,会搞砸你:words += wordsCount++;but 不是数字为 0 的原因。你应该将此代码放在单独的行中。您应该在 行的所有单词都被计算后添加到单词。

标签: java input java.util.scanner


【解决方案1】:

几个问题(实际上你的代码有很多问题,但我会解决与你发布的输出直接相关的问题):

首先,catch 块中的内容只有在您获得FileNotFoundException 时才会发生;在那里可以处理错误并从错误中恢复。我怀疑你打算在那里放一个finally 块,或者你打算在catch 之后这样做。我建议阅读catching and handling exceptions 上的本教程,它直接描述了try、catch 和finally。

阅读完该教程后,请回到您的代码;你可能会发现你有一些重组工作要做。

其次,考虑到上述情况,您看到的输出很明显您正在执行catch 块中的代码,这意味着您将获得FileNotFoundException。这可能是由以下两种(可能很明显)之一引起的:

  1. 没有找到您输入的文件。它可能不存在,也可能不在您期望的位置。检查以确保您输入了正确的文件名并且该文件确实存在。

  2. input 字符串不是您所期望的。也许您从之前的输入中读取了一个空白行等。

解决原因 2:如果无论出于何种原因,输入缓冲区中已经有一个换行符,您将读取一个带有Scanner 的空行。您可能希望在打开文件之前打印input 的值,以确保它是您所期望的。

如果您看到空白行,请跳过它们。所以,而不是这个:

String input = in.nextLine();
scanner = new Scanner(new File(input));     

这样的东西不会受到空行的影响:

String input;
do {
    input = in.nextLine().trim(); // remove stray leading/trailing whitespace
} while (input.isEmpty()); // keep asking for input if a blank line is read
scanner = new Scanner(new File(input));

最后,我认为您可以找出在输出中看到 0 的原因。当您尝试使用new Scanner(new File(input)); 打开文件并且由于找不到文件而失败时,它会引发异常并且程序会立即跳转到您的catch 块中的代码。这意味着 lines、words 和 chars 的初始值仍然为零(所有修改它们的代码都被跳过了)。

希望对您有所帮助。

【讨论】:

  • 我做了一些重构。用input 将这个棘手的时刻更改为JFileChooser,但它一直抛出file not found 并关机? update version with JFileChooser
  • 我刚刚尝试了您的更新版本(现在看起来好多了,文件选择器是个好主意)。我用文件选择器选择了一个文本文件,它打开它并运行得很好。 FileNotFoundException 的错误消息是什么?此外,您应该在问题中发布更新的代码,以便其他可能想要贡献的人知道它。 :)
  • 我解决了这个问题,因为我使用的是 Ubuntu 并且没有足够的权限。但它应该继续再次询问下一个输入文件,并且只有当您提供错误文件(不存在)时才为所有反制数据提供最终部分......
【解决方案2】:

您的 println()s 在 catch 块中

    } catch (FileNotFoundException e) {
        System.out.printf("All lines: %d\nAll words: %d\nAll chars: %d\n", 
                lines, words, chars);
        System.out.println("The end");
        done = true;
    }

这意味着你抓住了FileNotFoundException。我想你可以从这里弄清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多