我在Java中创建了一个应用程序,它计算所有数字的总和,直到命令行中的输入.
但是,如果在命令行中输入double或string,我需要显示一条错误消息,指出只能放入实数.
我怎样才能做到这一点?我认为它需要异常或其他什么?
public static void main(String[] args) {
right here?
int n = Integer.parseInt(args[0]);
Run Code Online (Sandbox Code Playgroud)
谢谢!
public static void main(String[] args) {
try {
int n = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
//here you print the error
System.out.println("Error: only real numbers can be put in");
//or
System.err.println("Error: only real numbers can be put in");
}
}
Run Code Online (Sandbox Code Playgroud)