Scanner method opened and closed twice

前端 未结 3 1115
说谎
说谎 2020-12-10 22:39

In a single class I have two different methods who are using the scanner class. I created a new instance of scanner object for the first method, then closed it at the end of

3条回答
  •  时光说笑
    2020-12-10 22:46

    I have been learning Java for a short time and don't really know what I am doing, but this worked for me. I have no idea why it did but...

    import java.util.Scanner;
    public class Inputing{
    
        public Scanner input_scan = null;
    
        public static int ScanningInput() {
            int input_value = 0;
            Scanner input_scan = new Scanner(System.in);
    
            try {
                input_value = input_scan.nextInt();
            } catch (Exception e) {
                System.out.println("!error!");
            } finally {
                if (input_scan.equals(null)) {
                    input_scan.close();
                }
            }
            return input_value;
        }
    
        public static int getInputA(int scan_valueA){
            scan_valueA = (ScanningInput());
            return scan_valueA;
        }
    
            public static int getInputB(int scan_valueB){
            scan_valueB = (ScanningInput());
            return scan_valueB;
        }
    }
    
    // then call it with another class
    
    public class MainClass{
    
        public static void main(String[] args) {
    
            int variableA = 0; 
            variableA = Inputing.getInputA(variableA);
    
            int variableB = 0;
            variableA = Inputing.getInputC(variableB);
        }
    
    }
    

    I apologize for any errors, and would appreciate guidance. I am a complete rookie but after messing with this code for a while, this seemed to produce no warnings and return the results I was looking for.

提交回复
热议问题