gpt4 book ai didi

java - 如何检查用户是否未输入任何内容以便显示错误消息

转载 作者:行者123 更新时间:2023-11-29 05:14:33 25 4
gpt4 key购买 nike

如果用户未提供命令行参数,我将尝试显示一条错误消息。当我在 cmd 中键入“java sheet12t1”时出现错误。我已经确定了程序的其余部分,只是这部分行不通。

下面是我正在处理的问题以及我的代码。

这是我正在处理的问题:http://i.imgur.com/Fv6901B.png

public class sheet12t1
{
public static void main(String[] args)
{
int projectCategory = Integer.parseInt(args[0]);
int keyServiceType = Integer.parseInt(args[1]);
if (args.length != 2)
System.out.println("Please enter: java sheet12t1 projectCategory serviceType");

else if (args.length == 0)
System.out.println("Please enter two valid inputs.");

else if (projectCategory < 1 || projectCategory > 3)
System.out.println("Please enter valid inputs.");

else if (keyServiceType < 1 || keyServiceType > 3)
System.out.println("Please enter valid inputs.");

else
{
double result = calculateProjectCost(projectCategory, keyServiceType);
System.out.println("Total project cost: " + result);
}
}

public static double calculateProjectCost(int projectCategory, int keyServiceType)
{
double totalCost = 10000;
if (projectCategory == 1)
{
if (keyServiceType == 1) totalCost += 5600.5;
else if (keyServiceType == 2) totalCost += 5500;
else totalCost += 6000;
}
else if (projectCategory == 2)
{
if (keyServiceType == 1) totalCost += 10600.5;
else if(keyServiceType ==2) totalCost += 11000;
else totalCost += 13500;
}
else
{
if (keyServiceType == 1) totalCost += 17000;
else if(keyServiceType == 2) totalCost += 22000;
else totalCost += 25000;
}
return totalCost;
}
}

最佳答案

开始使用前需要检查arguments数组的长度,错误退出,修改:

    int projectCategory = Integer.parseInt(args[0]);
int keyServiceType = Integer.parseInt(args[1]);

if (args.length != 2)
System.out.println("Please enter: java sheet12t1 projectCategory serviceType");

    if (args.length != 2) {
System.out.println("Please enter: java sheet12t1 projectCategory serviceType");
System.exit(1);
}

int projectCategory = Integer.parseInt(args[0]);
int keyServiceType = Integer.parseInt(args[1]);

取自https://stackoverflow.com/a/2670980/621366简短解释为什么 System.exit(0)System.exit(1)

The "0" lets whomever called your program know that everything went OK. If, however, you are quitting due to an error, you should System.exit(1);, or with another non-zero number corresponding to the specific error.

关于java - 如何检查用户是否未输入任何内容以便显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27037251/

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