我是 Java 的新手,所以我想请原谅这个相当简单的问题。此方法将仅计算 POSITIVE 整数上有多少位数字。所以它需要向调用者抛出一个错误。当输入为负时,我该怎么做,抛出错误并退出方法而不返回任何内容?
public static int countDigits(int n)
{
if (n<0)
{
System.out.println("Error! Input should be positive");
return -1;
}
int result = 0;
while ((n/10) != 0)
{
result++;
n/=10;
}
return result + 1;
}
最佳答案
你不会在这里抛出错误;您正在显示错误消息并返回标记值 -1
。
如果你想抛出一个错误,你必须使用throw
关键字,然后是一个合适的Exception
。
public static int countDigits(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input should be positive");
}
int result = 0;
while ((n / 10) != 0) {
result++;
n /= 10;
}
return result + 1;
}
Java Trails关于抛出异常的内容将为您提供宝贵的见解,让您了解存在哪些不同类型的异常。上面,IllegalArgumentException
被认为是运行时异常,因此调用此方法的对象不会被迫捕获其异常。
关于java - 如果方法参数无效则抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32506754/