我以这种方式编写代码,其中方法division在除两个整数后返回双精度值。它的工作很好,如果我不包括try catch块。但是,当我将带有类型转换的整数除法括在try块内时,就会导致编译问题,如下所示…请解决我的问题。
import java.util.Scanner;
class Division {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Division div=new Division();
System.out.println("Enter the two numbers to perform division operation:");
int x=sc.nextInt();
int y=sc.nextInt();
div.division(x,y);
}
public double division(int x,int y){
try{
double z=(double)(x/y);
return z;
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
}
}
在除法函数中缺少一个返回。通过捕捉异常,你说你要做一些事情来处理它,在出现问题的情况下,执行将继续。
最好在这里抛出异常,因为如果除以0,将不会返回任何结果。也可以返回一些无意义的东西,比如-1
public double division(int x,int y){
try{
double z=(double)(x/y);
return z;
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
return -1;
}
一个更好的解决方案是在除数为0时抛出异常,然后在使用除数的任何地方处理它
public double division(int x, int y) throws ArithmeticException {
if (y == 0)
throw new ArithmeticException("Cannot divide by 0");
double z = (double) (x / y);
return z;
}
您的方法缺少return
语句。试试这个
public double division(int x,int y){
double z=0.0;
try{
z=(double)(x/y);
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
return z;
}
你的方法必须有一个return
语句。
你当前的代码没有return
语句,如果它进入catch
块。
试试这段代码。
import java.util.Scanner;
public class Division {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Division div = new Division();
System.out.println("Enter the two numbers to perform division operation:");
int x = sc.nextInt();
int y = sc.nextInt();
div.division(x, y);
}
public double division(int x, int y) {
double z = 0;
try {
z = (double) (x / y);
} catch (ArithmeticException ae) {
ae.printStackTrace();
}
return z;
}
}
Live Demo here
.
而且我猜在类型转换的方式中有数据丢失。
如果17/3 = 5.6666666
是您想要的,那么您的代码是WRONG,因为x
和y
是int
。使用当前代码将得到的输出是17/3=5
您需要 z = (double) x / (double) y;
z = (double) (x / y);
问题是,如果您的try块失败,则没有找到返回语句(因为您提供的返回仅针对try块)。
因此,正如其他人指出的那样,您可以在之外返回一些东西(例如-1) try和catch块(但仍然在方法中),或者您也可以在catch块中使用return语句,这样即使try抛出异常,您的方法仍然返回double类型。