Can I have macros in Java source files

后端 未结 8 2520
情话喂你
情话喂你 2020-11-28 03:15

In my program I\'m reading integers form console many times. Every time, I need to type this line.

new Scanner(System.in).nextInt(); 

I\'m

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 04:16

    Use a utility class and static import.

    The utility class:

    package my.utils;
    
    public class ScannerUtils {
      private ScannerUtils() {}
    
      public static int readInt() {
        return new Scanner(System.in).nextInt();
      }
    }
    

    Using the utility class:

    package my.examples;
    
    import static my.utils.ScannerUtils.*;
    
    class Example {
      void foo() {
        int i = readInt();
      }
    }
    

    As others have said, you should probably cache your scanner, but that is a separate topic.

提交回复
热议问题