2011-10-28 17 views
2

forループを使用してキーボードから2つの数字を取得する必要があるクラスのプログラムを作成しています。プログラムは、最初の数値を2番目の数値の累乗に上げる必要があります。 forループを使用して計算を行います。 inum3が初期化されていないというエラーが出ています(私はループが決して入力できないかもしれないと理解しています)。しかし、この作業を行う方法を理解できません。 25行目と28行目は具体的なものです。あなたは、変数inum3を初期化する必要が変数を初期化するにはどうすればよいですか?

import javax.swing.*; 


    public class Loop2 
{ 
    public static void main(String[] args) 
    { 


    int inum1, inum2, inum3, count; 
    String str; 

    str = JOptionPane.showInputDialog("Please Enter a Numer"); 
    inum1 = Integer.parseInt(str); 

    str = JOptionPane.showInputDialog("Please Enter a Numer"); 
    inum2 = Integer.parseInt(str); 


    for (count = 1; count == inum2; count+=1) 
    { 
    inum3 = inum3 * inum1; 
    } 

    JOptionPane.showMessageDialog(null, String.format ("%s to the power of %s = %s", inum1,inum2, inum3), "The Odd numbers up to" + inum1,JOptionPane.INFORMATION_MESSAGE); 
}//main 
    }// public 

答えて

3

。あなたのプログラムが

inum3 = inum3 * inum1;

inum3を実行しようとしたとき、それは、今の現状では、それは乗算を行うことができないので、値を持ちません。

この場合は1にしたいと思います。あなたが自分自身を定義するために何かを使用しCANDので

ので、代わりの

int inum1, inum2, inum3, count;

あなたは

int inum1, inum2, inum3 = 1, count;

+0

私の宣言でinum3の値を変更しましたが、私が今問題になっているのは、コードの最下部に表示されるJoptionpaneが、ループ内に新しい値セットを表示するための "1"を表示していることです。 – user1018865

+0

その枠をforループに移動すると、それはまったく表示されません。 – user1018865

+0

printlnを追加して、ループの完了後にinum3が正しいことを確認します。あなたは間違いなくペインをループに入れたくありません。 – hvgotcodes

1
import javax.swing.JOptionPane; 

public class Loop2 { 
    public static void main(String[] args) { 

     int base, exp, result = 1; 
     String str; 

     str = JOptionPane.showInputDialog("Please Enter a Number"); 
     base = Integer.parseInt(str); 

     str = JOptionPane.showInputDialog("Please Enter an Exponent"); 
     exp = Integer.parseInt(str); 

     for (int count = 0; count < exp; count++) { 
      result *= base; 
     } 

     JOptionPane.showMessageDialog(null, String.format("%s to the power of %s = %s", base, exp, result), 
       "The Odd numbers up to" + base, JOptionPane.INFORMATION_MESSAGE); 
    } 
} 
+0

ありがとう、私は今私がやっていたことを理解しています! – user1018865

2

が1にNUM3を初期化できます。

num3 = 1;

関連する問題