为什么我的Java代码中会出现DivideByZeroException?

时间:2011-10-24 00:01:11

标签: java

import java.io.IOException;
import java.util.*;

public class calling {
public static String s;
public static String t;
public static int y;
public static int x;

public static int num1() {
int x;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number called x: ");
x=scanner.nextInt();
return x;    
}

public static int num2() {
int y;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number called y: ");
y=scanner.nextInt();
return y;    
}

public static void calculation() {
Scanner input = new Scanner(System.in);

System.out.println("What process would you like to do? *, /, + or - ?");
s=input.next();

if (s.equals("*")) {
System.out.println("\nThe product of these numbers is:" + (x*y));}
else 
if (s.equals("+")) {
System.out.println("\nThe sum of these numbers is: " + (x+y));}

System.out.println("\nDo you want x or y to be the dividor/subtractor?: ");
t=input.next();

if (t.equals("y") || t.equals("Y") ) {

if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is:  " + (x/y));}
else 
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + (x-y));}}

else 
if (t.equals("x") || t.equals("X")){

if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (y/x));}
else 
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + ((y-x)));}}
}

public static void  main (String [] args) throws IOException {


num1();
num2();
calculation();


}

}

我不断得到这个错误应该是我的最终结果,这只是执行计算的结果

这是错误:“线程中的异常”主“java.lang.ArithmeticException:/由零 在calling.calculation(calling.java:44) 在calling.main(calling.java:64)“

2 个答案:

答案 0 :(得分:2)

由于这可能是家庭作业,我会给你一个提示,指出你正确的方向。

运行程序时,执行num1num2以从用户收集xy的值。在num2内,y被声明为局部变量。当num2返回时,该变量会发生什么?那对于第7行声明的类字段(变量)y意味着什么?

这也是学习如何使用调试器的好时机。在第44行放置一个断点,看看xy的值是什么。

答案 1 :(得分:0)

你需要确保:

int x;
int y;

是你想要的。静态时整数默认为零。