再次需要帮助。该程序是将输入作为年龄并根据输入抛出异常。程序运行时会从命令行获取用户的年龄,如果用户没有在命令行输入数字或输入错误,程序应该处理问题。
我的代码是:
public class Age2 {
public static void main(String args[]){
try{
int age = Integer.parseInt(args[0]); //taking in an integer input throws NumberFormat Exception if not an integer
if(age<= 12)
System.out.println("You are very young");
else if(age > 12 && age <= 20)
System.out.println("You are a teenager");
else
System.out.println("WOW "+age+" is old");
}
catch(NumberFormatException e){ //is input is not an integer, occurs while parsing the command line input argument
System.out.println("Your input is not a number");
}catch(ArrayIndexOutOfBoundsException e){ //as takes in input from command line which is stored to a Args array in main, if this array is null implies no input given
System.out.println("Please enter a number on the command line");
}
}
}//end class
我得到的输出:
但如果用户犯了任何错误,程序也应该显示异常:
“22 22”或“3 kjhk”
见下图:
你能帮我修改一下吗? 谢谢大家。
最佳答案
如果传递 22 22kjj
,args 将有两个元素:22
和 22kjj
。
您可以添加一个条件:if(args.length != 1) System.out.println("only one number");
关于Java 程序从命令行获取输入,并进行异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29627430/