英文:
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 = "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("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selections: ");
String selection = keyboardInput.next();
switch (selection) {
case "1":
subStringProblem();
case "2":
pointsProblem();
case "3":
System.out.println("Good Bye!");
System.exit(0);
default:
System.out.println("Invalid option. Try again.");
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("File doesn't exist. Exiting.");
System.exit(0);
}
System.out.println("Substring problem.");
System.out.println("Enter a Substring:");
Scanner keyboardInput = new Scanner(System.in);
String subString = keyboardInput.next();
System.out.print(subString);
System.out.println();
String notFound = " - not found";
String infixFound = " - infix";
String prefixFound = " - prefix";
String suffixFound = " - suffix";
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("Points problem.");
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("DICTIONARY.txt");
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
else {
System.out.println("File doesn't exist. Exiting.");
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("DICTIONARY.txt");
if (fileReader.exists() == false) {
System.out.println("File doesn't exist. Exiting.");
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("File doesn't exist. Exiting.");
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论