有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。scanner如何在java中创建多个scanner元素

我有一个主函数,其中我使用scanner从控制台读取一个整数。 在这个主函数中,我们可以访问另一个函数,它也使用scanner读取整数。因此,程序多次在这两个函数之间摇摆。但是,Java。util。扫描程序抛出一个异常。有没有办法克服这个问题

import java.util.Scanner;

public class dummy {

    public static void main(String[] args) {

        int buy;  

        Scanner sc = new Scanner(System.in);
        buy = sc.nextInt();
        user = dummy2();
        sc.close();
    }

    static boolean dummy2(){

        Scanner sc1 = new Scanner(System.in);
        sc1.close();
    }
}

共 (3) 个答案

  1. # 1 楼答案

    使用相同的扫描仪对象

    import java.util.Scanner;
    
    public class dummy {
    
    private static final Scanner sc = new Scanner(System.in);
    
    public static void main(String[] args) {
    
        int buy;  
    
        buy = sc.nextInt();
        user = dummy2();
    //Do more stuff with the same scanner
    //close it when done
    
    
    }
    
    static boolean dummy2(){
    //Scan stuff
    int nbr = sc.nextInt();
    
    }
    
  2. # 2 楼答案

    我建议这样做:

    import java.util.Scanner;
    
    public class dummy {
        Scanner sc = new Scanner(System.in);
    
        public static void main(String[] args) {
    
            int buy;  
    
            buy = sc.nextInt();
            user = dummy2();
            sc.close();
    
        }
    
        static boolean dummy2(){
            //lets scan a string.
            sc.nextLine();
        }
    }
    

    可重用对象!这不是很好吗

  3. # 3 楼答案

    首先,如果您提供更多信息,例如异常及其消息,可能还有源代码,这将使问题更容易回答

    如果异常是NoTouchElementException,那么直接的问题是函数正在关闭扫描仪。当扫描仪关闭时,它也会关闭底层输入流。这会使该输入上的所有其他扫描仪无效

    如果异常为InputMismatchException,则输入不是int

    如果异常是IllegalStateException,那么扫描器已经关闭,如果函数和主要方法正在使用扫描器,那么可能会发生这种情况,然后关闭扫描器

    但是,您不应该在函数中接受用户输入。这限制了将来的使用,比如说,如果你想以后添加一个GUI,或者根据用户没有得到的数字进行相同的计算,那么你需要重写函数。函数应该以int作为参数,main方法应该从用户那里获取该参数。只有主方法和其他与用户输入直接相关的方法,例如扫描仪的方法,才应该读取用户输入