您好我正在尝试编写一个基本程序,让我输入2个数字,然后自动计算总和,差值,除法和余数,然后将结果打印到输出。这是我到目前为止所拥有的。它编译但我收到此错误
java.lang.ArithmeticException: / by zero
at Q1A3.DoTheCalculation(Q1A3.java:33)
at Q1A3.<init>(Q1A3.java:24)
当我尝试运行它时。我没有java经验,这是我第一次在电脑上尝试任何东西而不是电子邮件。请温柔!你能指出我的错误并指导我修复它们吗?谢谢。
/*
This program accepts two numbers from the user. Finds out the sum, diff, division and
remainder of the two numbers, and prints the results on the screen
*/
public class Q1A3
{
//instant variables - replace the example below with your own
private int a;
private int b;
private int sum;
private int difference;
private int division;
private int remainder;
//-----------------------------------------
//The following is the constructor that takes the input from the user
//and stores it in the system
public Q1A3(int a, int b)
{
DoTheCalculation ( );
PrintTheResults ( );
}
//-------------------------------------------------------------
//The following routine does all of the required calculations.
public void DoTheCalculation ( )
{
sum = (a+b);
difference = (a-b);
division = (a/b);
remainder = (a%b);
}
//----------------------------------------------------------------------------
//The following routine prints all of the information including the calculated
//items on the screen
public void PrintTheResults ( )
{
System.out.println("The value of “a” is:");
System.out.println("The value of “b” is:");
System.out.println("The sum is:" );
System.out.println("The difference is:");
System.out.println("The division is:");
System.out.println("The remainder is:");
}
}
答案 0 :(得分:1)
您不会为a或b指定任何值。试试这个:
private int a = 5;
private int b = 7;
答案 1 :(得分:1)
(1)确保从构造函数参数初始化私有成员变量。 (2)确保将变量分配给字符串输出。
请遵守以下源代码中的建议更改:
public Q1A3(int a, int b)
{
this.a = a;
this.b = b;
DoTheCalculation ( );
PrintTheResults ( );
}
public void PrintTheResults ( )
{
System.out.println("The value of 'a' is:"+a);
System.out.println("The value of 'b' is:"+b);
System.out.println("The sum is:" +sum);
System.out.println("The difference is:"+difference);
System.out.println("The division is:"+division);
System.out.println("The remainder is:"+remainder);
}
public static void main(String [] args)
{
Q1A3 obj = new Q1A3(8,4);
}
答案 2 :(得分:0)
您的答案位于错误代码“/ by”的第一行。你不能除以零(它会破坏宇宙或其他东西。)尝试使用if语句来测试是否传递0,拒绝或跳过它。
答案 3 :(得分:0)
你不能除以零(它会破坏宇宙或其他东西。)
~Andrew
不,它会造成黑洞。或者其他东西:P
问题已得到解答。但是:
自己(下次)找到错误的好方法是一个好的调试器或系统输出,例如System.out.println("var a:"+a)
在错误发生之前查看当时变量的值。