如何在不关闭扫描的情况下使ONE静态扫描仪全局变量成为常数,并在方法和main方法中使用它? [英] How to make a ONE static scanner global variable without closing scan constantly and use it within methods and the main method?

查看:102
本文介绍了如何在不关闭扫描的情况下使ONE静态扫描仪全局变量成为常数,并在方法和main方法中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个静态扫描仪,但是我想在它周围放置try catch块,以便它可以自动关闭以避免资源 泄漏和/或此异常:

I want to create a static scanner but i will like to put the try catch block around it so it can automatically close avoiding resources leaks and or this exception:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1585)
    at softwareEngineer.UserApp1.main(UserApp1.java:82)

基本上,我只想创建一个静态扫描仪声明,并在整个主程序中使用它,并包括静态方法,这时我的代码将要求为每种方法创建单独的扫描仪,并且您必须强制执行"scan.close() ".由于多个扫描器已打开但未关闭程序,因此下面的代码将收到异常处理错误.

Essentially I only want to create one static scanner declaration and use it throughout the main program and includes the static methods, at this point my code will require to create separate scanner for each method and you are force "scan.close()". the code below will recieve a exception handling error due to multiple scanner that was open and did not closein the program.

我更新了代码,现在我得到了空指针异常

I updated the code now i get null pointer exception

import java.util.Scanner;

public class UserApp1 {
    static User currentCustomer = null; //single object
    static Scanner scan;
    //------------------------------------------------------- 
    // Create a list, then repeatedly print the menu and do what the 
    // user asks until they quit 
    //------------------------------------------------------- 
    public static void main(String[] args) {

     scan = new Scanner(System.in);)//scanner to avoid resource leak
            printMenu(); //print menu system from another function
            String choice = scan.nextLine(); //reads an input
            final String EXIT_now = "0";
            final String BACK = "back";
               while (!(choice.equalsIgnoreCase(EXIT_now))){

          switch(choice) {
                 case 1: break;
                             case 2: 
                               currentCustomer = loginInput();<---- errors happens here
                if(currentCustomer != null){
                    System.out.println("You have successfully login");
                }
                break;
                default: 
                    System.out.println("Sorry, invalid choice"); 
                    break;
                } //ends switch  
                printMenu(); //print menu system from another function
                choice = scan.nextLine(); //reads an input
            }//ends while 

    System.out.println("\t\t GoodBye!\n Thank you for trying our program.");           
        System.exit(0);
    }//ends main

    //---------------------------- 
    // Print the user's choices 
    //---------------------------- 
    public static void printMenu() { 
        System.out.println("\t\t The User Login System "); 
        System.out.println("\t\t ======================"); 
        System.out.println("The Menu Options:"); 
        System.out.println("1: Register an Account");
        System.out.println("2: Login to your Account");
        System.out.println("3: Reset Password");
        System.out.println("0: Quit/Exit ");

        System.out.println("Please enter your selection > "); 
    } //ends printMenu 

      public static User loginInput(){

         System.out.print( "\nFollow the Prompts to Log-In to your Account  \n ");
            System.out.print( "\nPlease enter your userid : \n ");
            String userid = scan.nextLine();// <---- errors happens here

            System.out.print( "\nPlease enter your password: \n ");
            String pass = scan.nextLine();

            currentCustomer = AccountList.loginUser(userid, pass);

            if (currentCustomer != null)
            {    
                return currentCustomer;
            }
            return null;
    }//ends loginInput

}//ends class*

推荐答案

通过将要使用的Scanner实例传递给相关方法,完全避免使用静态全局Scanner.请考虑以下简化示例:

Avoid using a static global Scanner at all, by passing the Scanner instance you want to work with to the relevant methods. Consider this simplified example:

public static void main(String[] args) {
  try(Scanner in = new Scanner(System.in)) {
    String choice = in.nextLine().trim();
    if(choice.equals("1")) {
      doOp1(in);
    } else if(choice.equals("2")) {
      doOp2(in);
    } else {
      System.err.println("Invalid choice.  Goodbye.");
    }
  }
}

// Method takes an open, functioning Scanner as an argument, therefore
// it doesn't need to close it, or worry about where it came from, it
// simply uses it, does what it needs to do, and returns, trusting
// the caller to properly close the Scanner, since it opened it.
private void doOp1(Scanner in) {
  System.out.print("What is your name? ");
  String name = in.nextLine().trim();
  System.out.print("What is your favorite color? ");
  String color = in.nextLine().trim();
}

private void doOpt2(Scanner in) {
  ...
}

您希望对资源进行划分,以确保它们的范围有限且易于关闭.将它们置于任何形式的全局状态都非常困难.而是,使用代码将资源的打开和关闭与代码分开.这种分隔使代码更易于维护,可读性和可测试性.

You want to compartmentalize your resources to ensure they are limited in scope and easy to close. Putting them in global state of any kind makes that very difficult. Instead, separate the opening and closing of the resource from the code using it. This sort of compartmentalization makes for much more maintainable, readable, and testable code.

例如,通过将已经打开的Scanner传递给核心业务逻辑功能,您可以模拟真实用户的行为并创建测试以确保您的代码保持稳定,方法是构造一个Scanner以读取硬编码的String,并将其传递到您的方法中,而无需运行整个类并一次又一次地手动输入测试的行为.

For instance, by passing an already open Scanner to your core business logic functions, you can mock a real user's behavior and create a test to ensure your code remains stable, by constructing a Scanner that reads from a hard coded String, and passing that into your method, without needing to run the whole class and type in the behavior your testing manually again and again.

这篇关于如何在不关闭扫描的情况下使ONE静态扫描仪全局变量成为常数,并在方法和main方法中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆