scanner.close() 当我使用 try/finally 时不起作用

scanner.close() Does not work when I use try/finally

提问人:Ilias Matrane 提问时间:4/12/2022 最后编辑:Robert HarveyIlias Matrane 更新时间:4/12/2022 访问量:199

问:

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)"
        }
    }
}
爪哇岛 try-catch(尝试捕捉) java.util.scanner try-catch-finally(尝试-捕捉-最后)

评论


答:

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();
        }
    }
}