英文:
How do you put an if statement inside of a try catch exception?
问题
你好,我正在处理一个读取文件并输出内容的方法。在我将if语句放入代码之前,代码是可以正常工作的,但我似乎无法解决if语句内部的异常部分。任何帮助将不胜感激!
public static void reader(String file, String argument) {
File myList = new File(file);
try {
Scanner in = new Scanner(myList);
while (in.hasNextLine()) {
String s = in.nextLine();
if(myList.equals(argument)){
System.out.print(s);
System.out.println();
}
else{
System.out.print("执行某些操作");
}
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
英文:
Hello I'm working on method that is reading a file and outputting something. My code worked before I put my if statement in the code, I can't seem to figure out the exception part with the if statement inside of it. Any help would be greatly appreciated!
public static void reader(String file, String argument) {
File myList = new File(file);
try {
Scanner in = new Scanner(myList);
while (in.hasNextLine()) {
String s = in.nextLine();
if(myList.equals(argument)){
System.out.print(s);
System.out.println();
}
else{
System.out.print("do something");
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
答案1
得分: -1
有3个点可能满足条件(I、II、III)。
try (Scanner in = new Scanner(myList)) {
if (!in.hasNextLine()) {
System.out.print("执行操作 I");
} else {
boolean uneq = false;
while (in.hasNextLine()) {
String s = in.nextLine();
if (myList.equals(argument)) {
System.out.print(s);
System.out.println();
} else {
System.out.print("执行操作 II");
uneq = true;
}
}
if (uneq) {
System.out.print("执行操作 III");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
英文:
There are 3 points where a condition could be met (I, II, III).
try (Scanner in = new Scanner(myList)) {
if (!in.hasNextLine()) {
System.out.print("do something I");
} else {
boolean uneq = false;
while (in.hasNextLine()) {
String s = in.nextLine();
if (myList.equals(argument)) {
System.out.print(s);
System.out.println();
} else {
System.out.print("do something II");
uneq = true;
}
}
if (uneq) {
System.out.print("do something III");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论