提问人:Ilias Matrane 提问时间:4/12/2022 最后编辑:Robert HarveyIlias Matrane 更新时间:4/12/2022 访问量:199
scanner.close() 当我使用 try/finally 时不起作用
scanner.close() Does not work when I use try/finally
问:
import java.util.Scanner;
public class userInput
{
public static void main(String[]args){
try{
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
int age = scanner.nextInt();
scanner.nextLine();
String text = scanner.nextLine();
System.out.println(name + "\n" + age + "\n" + text);
//scanner.close(); //it works here
}
finally{
scanner.close(); // does not work here"scanner cannot be resolvedJava(570425394)"
}
}
}
答:
0赞
Ali
4/12/2022
#1
您必须在“尝试”之前定义扫描仪,所以没关系,现在这是您的代码:
import java.util.Scanner;
public class userInput {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
try {
String name = scanner.nextLine();
int age = scanner.nextInt();
scanner.nextLine();
String text = scanner.nextLine();
System.out.println(name + "\n" + age + "\n" + text);
}
finally {
scanner.close();
}
}
}
评论