Can I have macros in Java source files

后端 未结 8 2531
情话喂你
情话喂你 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();
       }
    }
    

提交回复
热议问题