2011-10-24 15 views
2
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コードでDivideByZeroExceptionが発生するのはなぜですか?

を行っている計算の結果である私の最終結果がどうあるべきかでこのエラーを取得しておいてください。メインの 『java.lang.ArithmeticException」スレッドでの例外』:/これはおそらく宿題ですので、ゼロcalling.mainでcalling.calculation(calling.java:44) (calling.java:64)で 」

+6

0で割ることはできません。それはインターネットを壊します。 – Joe

+0

私は0で除算しませんでした。試してみてください...私は25/5でこの正確なエラーを受け取りました。 –

+0

いいえ、あなたはしませんでした。もう一度見てください。 – EJP

答えて

2

で、私はあなたの右にあなたを指すようにヒントを与えるだろう方向。あなたがプログラムを実行すると

は、ユーザーからxyの値を収集するためにnum1num2を実行します。 num2の範囲内では、yがローカル変数として宣言されます。 num2が返ってくると、その変数はどうなりますか?そしてそれは、クラスフィールド(変数)yが7行目で宣言したことを意味しますか?

これは、デバッガの使い方を学ぶのにも適しています。 44行目にブレークポイントを置き、xyの値が何であるかを確認してください。あなたがいることを確認する必要があり

+0

その宿題ではありません(ちょっとした課題が私は自分自身にJavaを学ぶために与えます)...しかし、助けてくれてありがとう! –

0

int x; 
int y; 

は、あなたが欲しいものです。 Integerは、静的な場合はデフォルトでゼロになります。

+0

ありがとう!私jsutはnum1とnum2から削除する必要があります。 –

関連する問題