簡體   English   中英

在提示和用戶輸入下使用掃描儀

[英]Using scanner with a prompt and user input

我試圖對用戶“輸入”文件中的行,單詞,字符進行計數。
此節目結束后,計數並繼續詢問。

如果文件不存在,則打印運行期間已計數的所有數據。

碼:

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.");
            }
        }
    }
}

幾個問題(實際上您的代碼有很多問題,但是我將解決與您發布的輸出直接相關的問題):

首先,僅當您收到FileNotFoundExceptioncatch塊中的內容才會發生; 在那里可以處理錯誤並從錯誤中恢復。 我懷疑你打算在那兒放一個finally方塊,或者你打算在catch那之后做。 我建議閱讀有關捕獲和處理異常的本教程,該教程直接描述了trycatchfinally

閱讀該教程后,請返回您的代碼。 您可能會發現您需要進行一些重組。

其次,考慮到以上幾點,從輸出中可以明顯看出,您正在執行該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));打開文件時new Scanner(new File(input)); 失敗,因為找不到文件,它引發異常,程序立即跳轉到catch塊中的代碼。 這意味着lineswordschars的初始值仍為零(跳過所有修改它們的代碼)。

希望能有所幫助。

您的println()位於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 我想你可以從這里弄清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM