java - 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.
解决方案
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.
推荐阅读
- android - 如何在 Horizontal ScrollView 或 RecycleView 中突出显示中心元素?
- python - Python 包需要 freeglut 作为依赖
- python - subprocess.Popen 尝试运行时出现 python 错误。在cmd中工作正常
- docker - Docker 容器的 npm 更新检查失败
- r - 如何使用 usmap 标记数字而不是名称?
- php - WAMP 上的 Laravel(Skote 安装)- 不支持 HTTP 方法
- git - 存储库 docker.io/not found:不存在或没有拉取访问权限
- tableau-api - 计算画面中的总百分比
- sql-server - 使用记录集将数据从 Oracle 传输到 SQL Server
- java - 如何从输入计算一组计算的平均值和最大值/最小值?