我有一个 java 程序,我想将其作为 jar 在命令行中运行。但在运行处理数据的函数之前,我需要满足 2 个条件。 1. args[0]
必须是整数。 2. 必须有 2 个参数。如果不满足这些条件,我希望弹出错误消息,然后系统退出。我想我可以做正确的第一件事,但是我如何将两者结合起来?
public static void main(String[] args) throws IOException
{
try
{
int x = Integer.parseInt(args[0]);
process(x, args[1]);
}
catch(NumberFormatException e)
{
System.output.println("Please enter an integer");
}
}
最佳答案
然后,这是您应该编写的代码:
public static void main(String[] args) throws IOException {
if(args == null || args.length != 2) {
System.out.println("You have not entered the required two parameters");
return;
}
try {
int x = Integer.parseInt(args[0]);
process(x, args[1]);
} catch (NumberFormatException e) {
System.out.println("Please enter an integer");
}
}
请注意,您的 System.output.println("请输入一个整数"); 中存在编译错误。声明,而是:
System.out.println("Please enter an integer");
关于java - 运行程序之前我需要满足的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15706728/