Reputation: 21
I'm writing a program for my class where I have to use a for loop to takes two numbers from the keyboard. The program should then raise the first number to the power of the second number. Use a for loop to do the calculation. I'm getting the error that inum3 is not being initialized (I understand because the loop may never enter) but I cannot figure out how to make this work. Line 25 and 28 to be specific.
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
Upvotes: 2
Views: 375
Reputation: 762
initialize num3 to one because you cand use something to define itself.
num3 = one;
Upvotes: 2
Reputation: 4597
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);
}
}
Upvotes: 1
Reputation: 120168
you need to initialize the variable inum3
. As it stands right now, when your program tries to execute
inum3 = inum3 * inum1;
inum3
has no value, so it can't do the multiplication.
I think you want it to be 1 in this case.
So instead of
int inum1, inum2, inum3, count;
you can do
int inum1, inum2, inum3 = 1, count;
Upvotes: 3