Can I have macros in Java source files

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

    Java does not support macros. IIRC, the language designers felt that macros and the resultant preparser was an unnecessary and undesirable complication.

    Use a function instead:

    public int readInt(Scanner inp) {
        return inp.nextint();
        }
    

    Elsewhere:

    Scanner input=new Scanner(System.in);
    
    ...
    
    
    int a=readInt(input);
    

    Note also, that I create the scanner once and reuse it.

提交回复
热议问题