JOptionPane.showMessageDialog does not display! HELP NEEDED

magic507

Beta member
Messages
4
Ok this is a simple program and should work..... I cannot figure out why it doesn't.

The user inputs a number, a for loop is initiated to calculate the factorial of the number, and prints the value to the screen.

IF the number is negative a message is displayed that the user must enter a positive number (MY MESSAGE DISPLAY DOESN'T WORK IF A NEGATIVE NUMBER IS ENTERED.... it just sits there and nothing happens).

Any help is appreciated.

import java.util.*;
import javax.swing.*;
public class Factorial {
public static void main(String[] args) {

int n; // variable to store number for which the factorial is to be calculated
int counter; // loop counter
int factorial; // factorial value

Scanner scan = new Scanner(System.in);

System.out.println(
"This program asks the user for a positive integer number,"
+ "\ncomputes the factorial value, and displays the answer."
+ "\nPlease enter a positive integer: ");
n = scan.nextInt();

if (n <= 0)
{
JOptionPane.showMessageDialog(null, "You must enter a positive number.");
}

factorial = 1;
for (counter = 1; counter <= n; counter++)
{
factorial *=counter;
}

System.out.println("The factorial of " + n +" is " +factorial);

}// end method main
}// end class Factorial
 
Well, I ran your program, and it seems to work just fine. I did make a couple changes, see if this helps you at all.
Code:
import java.util.*;
import javax.swing.*;
public class Factorial {
 static Factorial f;
public static void main(String[] args) {
int n = -1; // variable to store number for which the factorial is to be calculated
int factorial; // factorial value
Scanner scan = new Scanner(System.in);
f = new Factorial();
System.out.println(
"This program asks the user for a positive integer number,"
+ "\ncomputes the factorial value, and displays the answer."
+ "\nPlease enter a positive integer: ");
do {
n = scan.nextInt();
if (n <= 0)
{
JOptionPane.showMessageDialog(null, "You must enter a positive number.");
System.out.printf("\n\t%s","Please enter a positive integer:");
} else {
 f.compute(n, 1);
}
} while(n < 0);
}// end method main
  public void compute(int number, int fact) {
   int counter;
   fact = 1;
   for (counter = 1; counter <= number; counter++)
   {
   fact *=counter;
   }
System.out.println("The factorial of " + number +" is " +fact);
}
public Factorial() {
}
}// end class Factorial
 
Back
Top Bottom