有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用main方法声明变量的最佳方法

嗨,我只是想知道在java中声明变量的最佳方式是:

在方法外部声明静态变量时:

    public class Copy {

   public static Scanner scanInput   =   new Scanner(System.in);
   public static String captureString;

    public static void main(String[] args){
        //Scanner scanInput   =   new Scanner(System.in);
        //String captureString;

        System.out.println("Please enter some words..");
        captureString   =   scanInput.nextLine();

        System.out.println("You entered: " + captureString);

    }

}

或者在主方法中使用变量:

    public class Copy {

   //public static Scanner scanInput   =   new Scanner(System.in);
   //public static String captureString;

    public static void main(String[] args){
        Scanner scanInput   =   new Scanner(System.in);
        String captureString;

        System.out.println("Please enter some words..");
        captureString   =   scanInput.nextLine();

        System.out.println("You entered: " + captureString);

    }

}

在这种情况下,哪种是声明变量的首选方式


共 (3) 个答案

  1. # 1 楼答案

    视情况而定。如果所有代码都在main方法中,那么在方法中声明变量。但是,如果其他方法或类需要访问它们,则需要全局声明它们。在这种情况下,最好将字段设置为本地字段,而不是全局字段

    另外,如果你希望你的变量不是静态的,你可以创建一个类的实例

     public class Copy {
    
       public Scanner scanInput   =   new Scanner(System.in);
       public String captureString;
    
        public static void main(String[] args){
           new Copy();
        }
        public Copy()
        {
            System.out.println("Please enter some words..");
            captureString   =   scanInput.nextLine();
    
            System.out.println("You entered: " + captureString);
        }
    
    
    }
    

    这样会浪费内存创建静态字段

  2. # 2 楼答案

    如果可以在main中声明变量,那么就这样做。但是,如果要调用同一类中的其他方法,并且这些方法需要访问相同的变量,则无法执行此操作(而且将它们作为参数传递太麻烦了)。在这种情况下,我倾向于将它们声明为类的非静态private成员,然后让main创建类的实例:

    public static void main(String[] args) {
        new Copy().doMain(args);
    }
    
    public void doMain(String[] args) {        // not static!
        // put your interesting stuff here
    }
    

    (如果你不打算使用它们,你不必通过args。)

  3. # 3 楼答案

    声明方法内部的变量!这不仅仅是我的观点,这是惯用的答案。另一个将为您提供功能代码,但它毫无目的地污染了静态名称空间。如果它们是常量(设计用于多个类),那么我可能会给你一个不同的答案