gpt4 book ai didi

java - 接受命令提示符参数并构造对象

转载 作者:行者123 更新时间:2023-12-02 05:22:38 25 4
gpt4 key购买 nike

我需要接受命令提示符参数,并使用它们来构造一个对象。我要带一些人和船的大小。

public RiverCrossingPuzzle(int numEach, int boatSize)

Creates a RiverCrossingPuzzle with numEach number of cannibals and numEach number of missionaries with a boat that can carry up to boatSize number of missionaries/cannibals. For example, the input can be "-n", "4", "-b", "3"

我应该这样做吗:

this.numEach = Integer.parseInt(args[2]);
this.boatSize = Integer.parseInt(args[4]);

或者像这样:

int numEach = Integer.parseInt(args[2]);
int boatSize = Integer.parseInt(args[4]);
this.boatSize = boatSize;
this.numEach = numEach;

最佳答案

在调用构造函数之前,我会读取并解析命令行参数。

public static void main (String[] args)
{
int numEach = 0; // or some other default value that makes sense
int boatSize = 0; // or some other default value that makes sense
if (args.length > 1)
numEach = Integer.parseInt(args[1]);
if (args.length > 3)
boatSize = Integer.parseInt(args[3]);
RiverCrossingPuzzle puzzle = new RiverCrossingPuzzle (numEach, boatSize);
}

您还应该添加异常处理,以防命令行参数无法以 int 进行解析。

顺便说一句,根据您的 "-n", "4", "-b", "3" 示例,您应该阅读 args[1] 并且args[3]

关于java - 接受命令提示符参数并构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26375678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com