
1个回答
展开全部
java的:说实话,没懂你的意思! (要求用异常处理输入错误。用其它方法(不是异常))
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个数字: ");
String s = sc.next();
double d = sqrt(s);
System.out.println(s+"开根后结果为:"+d);
}
static Double sqrt(String s) {
if (s == null) {
throw new NullPointerException("未输入数字");
}
s = s.trim();
try {
double d = Double.parseDouble(s);
if (d < 0) {
throw new RuntimeException("负数不能开平方根");
}
return Math.sqrt(d);
} catch (NumberFormatException e) {
throw new NumberFormatException("输入的数字有误");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个数字: ");
String s = sc.next();
double d = sqrt(s);
System.out.println(s+"开根后结果为:"+d);
}
static Double sqrt(String s) {
if (s == null) {
throw new NullPointerException("未输入数字");
}
s = s.trim();
try {
double d = Double.parseDouble(s);
if (d < 0) {
throw new RuntimeException("负数不能开平方根");
}
return Math.sqrt(d);
} catch (NumberFormatException e) {
throw new NumberFormatException("输入的数字有误");
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询