如何使类变量文件检查在打印行而不是抛出异常时显示。

huangapple go评论76阅读模式
英文:

How to get class variable file check to print line rather than throw exception

问题

这是您提供的代码的翻译部分:

我正在尝试创建一个用于检查文件存在性并打印文件不存在消息的方法但它必须是一个类变量而不是实例变量

在仅位于subString方法中不是类变量以及没有中缀/后缀/前缀代码时它是可以工作的

以下是我的代码它仍然有些混乱并且不符合格式约定

感谢您的帮助

package wordgames;

import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;

public class WordGames {

    private static final String DICTIONARY = "dictionary.txt";
    private static String[] wordsCollection;
    private static int wordCount = 0;

    public static void main(String[] args) throws Exception {
        wordsCollection = new String[100];
        File fileReader = new File(DICTIONARY);
        Scanner fileScanner = new Scanner(fileReader);

        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine();
            wordsCollection[wordCount] = line;
            wordCount++;
        }

        getSelection();
    }

    static String getSelection() throws FileNotFoundException {
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("欢迎使用Word Games程序菜单。");
        System.out.println("从以下选项中选择一个。");
        System.out.println("1. 子字符串问题。");
        System.out.println("2. 得分问题。");
        System.out.println("3. 退出。");
        System.out.println("输入您的选择:");
        String selection = keyboardInput.next();

        switch (selection) {

        case "1":
            subStringProblem();
        case "2":
            pointsProblem();
        case "3":
            System.out.println("再见!");
            System.exit(0);
        default:
            System.out.println("无效选项。请重试。");
            getSelection();
        }

        return null;
    }

    static void subStringProblem() throws FileNotFoundException {
        File fileReader = new File("DICTIONARY.txt");
        Scanner fileScanner = new Scanner(fileReader);
        if (fileReader.isFile() == true) {
        } else {
            System.out.println("文件不存在。正在退出。");
            System.exit(0);
        }
        System.out.println("子字符串问题。");
        System.out.println("输入一个子字符串:");
        Scanner keyboardInput = new Scanner(System.in);
        String subString = keyboardInput.next();
        System.out.print(subString);
        System.out.println();
        String notFound = " - 未找到";
        String infixFound = " - 中缀";
        String prefixFound = " - 前缀";
        String suffixFound = " - 后缀";

        for (int i = 0; i < wordCount; i++) {
            String temp = wordsCollection[i];

            boolean found = false;

            if (wordsCollection[i].startsWith(subString)) {
                found = true;
                temp = temp + prefixFound;
            }

            if (wordsCollection[i].endsWith(subString)) {
                found = true;
                temp = temp + suffixFound;
            }

            if (wordsCollection[i].contains(subString)) {
                found = true;
                temp = temp + infixFound;
            }

            if (!found) {
                System.out.printf(" " + wordsCollection[i] + notFound + "\n");
            } else {
                System.out.printf(" " + temp + "\n");
            }

        }

        getSelection();
    }

    private static void pointsProblem() throws FileNotFoundException {
        System.out.println("得分问题。");
        getSelection();
    }
}

请注意,代码中的一些字符转义已被修复,以使其能够正确显示中文和引号。如果您有任何其他问题,请随时提出。

英文:

I'm trying to get a method to check for the existence of a file, and print a message that the file doesn't exist, but it also has to be a class variable rather than an instance variable.

I had it working when it was only in subString method, was not a class variable and without infix/suffix/prefix code.

Here is my code. It's still a little bit messy and no conforming to formatting convention.

Appreciate your help.

package wordgames;
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class WordGames {
private static final String DICTIONARY = &quot;dictionary.txt&quot;;
private static String[] wordsCollection;
private static int wordCount = 0;
public static void main(String[] args) throws Exception {
wordsCollection = new String[100];
File fileReader = new File(DICTIONARY);
Scanner fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
wordsCollection[wordCount] = line;
wordCount++;
}
getSelection();
}
static String getSelection() throws FileNotFoundException {
Scanner keyboardInput = new Scanner(System.in);
System.out.println(&quot;Welcome to the Word Games program menu.&quot;);
System.out.println(&quot;Select from one of the following options.&quot;);
System.out.println(&quot;1. Substring problem.&quot;);
System.out.println(&quot;2. Points problem.&quot;);
System.out.println(&quot;3. Exit.&quot;);
System.out.println(&quot;Enter your selections: &quot;);
String selection = keyboardInput.next();
switch (selection) {
case &quot;1&quot;:
subStringProblem();
case &quot;2&quot;:
pointsProblem();
case &quot;3&quot;:
System.out.println(&quot;Good Bye!&quot;);
System.exit(0);
default:
System.out.println(&quot;Invalid option.  Try again.&quot;);
getSelection();
}
return null;
}
static void subStringProblem() throws FileNotFoundException {
File fileReader = new File(&quot;DICTIONARY.txt&quot;);
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
} else {
System.out.println(&quot;File doesn&#39;t exist.  Exiting.&quot;);
System.exit(0);
}
System.out.println(&quot;Substring problem.&quot;);
System.out.println(&quot;Enter a Substring:&quot;);
Scanner keyboardInput = new Scanner(System.in);
String subString = keyboardInput.next();
System.out.print(subString);
System.out.println();
String notFound = &quot; - not found&quot;;
String infixFound = &quot; - infix&quot;;
String prefixFound = &quot; - prefix&quot;;
String suffixFound = &quot; - suffix&quot;;
for (int i = 0; i &lt; wordCount; i++) {
String temp = wordsCollection[i];
boolean found = false;
if (wordsCollection[i].startsWith(subString)) {
found = true;
temp = temp + prefixFound;
}
if (wordsCollection[i].endsWith(subString)) {
found = true;
temp = temp + suffixFound;
}
if (wordsCollection[i].contains(subString)) {
found = true;
temp = temp + infixFound;
}
if (!found) {
System.out.printf(&quot; &quot; + wordsCollection[i] + notFound + &quot;\n&quot;);
} else {
System.out.printf(&quot; &quot; + temp + &quot;\n&quot;);
}
}
getSelection();
}
private static void pointsProblem() throws FileNotFoundException {
System.out.println(&quot;Points problem.&quot;);
getSelection();
}
}

答案1

得分: 1

我注意到你在所有函数的签名中都加了 throws FileNotFoundException。只有在你不想在函数内部捕获异常,希望调用者负责处理异常时才这样做。在你的程序中,从未出现这种情况,你总是希望立即处理异常并退出,所以请从所有地方移除这部分代码。

导致你的代码崩溃的部分:

File fileReader = new File("DICTIONARY.txt");
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
else {
  System.out.println("文件不存在。退出。");
  System.exit(0);
}

如果你移除 fileScanner,这段代码将正常工作。它会在文件不存在时抛出异常,但由于你实际上没有在任何地方使用它,所以可以将其移除。fileReader.isFile() 检查将会完成这个工作。(fileReader.exists() 更接近实际情况)

修正后的代码:

File fileReader = new File("DICTIONARY.txt");

if (fileReader.exists() == false) {
  System.out.println("文件不存在。退出。");
  System.exit(0);
}

main() 函数中,你也在读取一个文件。这里你实际上使用了 fileScanner,所以可以选择使用与上述相同的检查,或者你实际上可以在这次捕获 FileNotFoundException,至少可以尝试一下。

try {
    File fileReader = new File(DICTIONARY);
    Scanner fileScanner = new Scanner(fileReader);

    while (fileScanner.hasNextLine()) {
        String line = fileScanner.nextLine();
        wordsCollection[wordCount] = line;
        wordCount++;
    }
} catch (FileNotFoundException e) {
    System.out.println("文件不存在。退出。");
    System.exit(0);
}

在 try/catch 块内部调用一个函数会是一个很好的实践,这将使代码看起来更加整洁。

英文:

I've noticed that you have put throws FileNotFoundException in the signature of all of your functions. You only do this if you don't want to catch the exception in that function, and want the caller to be responsible for handling the exception. In your program, that is never the case, you always want to handle it immediately by exiting, so remove it from everywhere.

The part of your code that is crashing:

File fileReader = new File(&quot;DICTIONARY.txt&quot;);
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
else {
  System.out.println(&quot;File doesn&#39;t exist.  Exiting.&quot;);
  System.exit(0);
}

This code will work if you remove the fileScanner. It throws an exception if the file doesn't exist, but since you're not actually using it for anything, you can just remove it. The fileReader.isFile() check will then do the job. (fileReader.exists() is closer to)

The corrected code:

File fileReader = new File(&quot;DICTIONARY.txt&quot;);

if (fileReader.exists() == false) {
  System.out.println(&quot;File doesn&#39;t exist.  Exiting.&quot;);
  System.exit(0);
}

You're also reading a file in the main() function. There you're actually using the fileScanner, so this gives you a choice of either using the same check as above, or you can actually catch the FileNotFoundException this time, you could try that at least to give it a try.

try {
    File fileReader = new File(DICTIONARY);
    Scanner fileScanner = new Scanner(fileReader);

    while (fileScanner.hasNextLine()) {
        String line = fileScanner.nextLine();
        wordsCollection[wordCount] = line;
        wordCount++;
    }
} catch (FileNotFoundException e) {
    System.out.println(&quot;File doesn&#39;t exist. Exiting.&quot;);
    System.exit(0);
}

It would be good practice if within the try/catch block you actually called a function, that would make stop it from looking ugly.

huangapple
  • 本文由 发表于 2020年10月8日 15:23:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64257636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定