首页 > 解决方案 > Constructors and unknown array sized; prompts in the main method (best practice)

问题描述

My problem is best solved a global array variable, say int[]. The size of the array comes from stdin.

Now, my constructor needs to initialize the array and the size needs to be known. Also in the main method I should only call Service.method(), and not call method() by itself. The problem becomes, " I should not call prompt() by itself, in main() to collect the array size. Also I cannot create class instance before having prompted the user to give the array size.

public class Class
    //variable
    int[] var;

    //constructor
    public Class(int size)
    {
        var = new int[size];
    }

    public int prompt()
    {
        Scanner input = new Scanner( System.in );
        return input.nextInt();
    }

    public static void main(String[] args)
    {
        //should not write 
        //prompt()

        //i don't know the size, can't call constructor
    }
}

In practice, this can be solved by implementing the prompt() within main(), and not in its own method. Is this good practice? Is there another customary solution to this problem?

Also, lists are really inconvenient for the purposes of this program and I would like to avoid using these if I can.

Thanks.

标签: java

解决方案


This could be done by implementing prompt() within main(), but another solution is to make prompt() static, like so:

public static int prompt()
{
    Scanner scanner = new Scanner(System.in);
    return scanner.nextInt();
}

Doing this makes is so that you can call it using Class.prompt() instead of requiring an instance of Class, and it is able to be a static method because it does not depend on any of the data in an instance of Class. It then becomes part of the overall class, instead of one instance of the class. Implementing the above, your usage would look like:

    public static void main(String[] args)
    {
        //Ask the size.
        int size = Class.prompt();
        //Create the class with the size asked for above.
        Class instance = new Class(size);
    }

I recommend you look into the Java Class Member Documentation.


推荐阅读