Can I have macros in Java source files

后端 未结 8 2355
情话喂你
情话喂你 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

    No. Java (the language) does not support macros of any sort.

    However, certain constructs can be faked or wrapped. While the example is silly (why are you creating a new scanner each time!?!?!) the below shows how it can be achieved:

    int nextInt() {
       return new Scanner(System.in).nextInt(); 
    }
    ...
    int a = nextInt();
    int b = nextInt();
    

    But much better:

    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    

    Happy coding.


    For comment:

    Static methods can be called without needing an object to invoke them upon. However, in most cases one is already in an object. Consider:

    public class Foo {
       static int nextIntStatic() {
         return 13;
       }
    
       int nextInt() {
         return 42;
       }
    
       void realMain () {
         // okay to call, same as this.nextInt()
         // and we are "in" the object
         int ni = nextInt();
       }
    
       public static void main(String[] args) {
          // okay to call, is a static method
          int nis = nextIntStatic();
          Foo f = new Foo();
          f.realMain();
       }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题