Can I have macros in Java source files

后端 未结 8 2525
情话喂你
情话喂你 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 doesn't support macros simply because the designers of Java chose not to include that functionality. The longer answer is that Java doesn't have a preprocessor the way C/C++ does and cannot perform that functionality that the preprocessor normally would. The way I would implement this is simply create a wrapper class that wraps up the Scanner constructor calls. Perhaps something like

    public static int readInt(){
      return new Scanner(System.in).nextInt();
    }
    

    Or, better yet,

    public class ScannerWrapper{
      private static Scanner instance = null;
    
      public static int readInt(){
       if (instance == null){
         instance = new Scanner(System.in);
       }
    
       return instance.nextInt();
     }
    

提交回复
热议问题