/* The following programs are written to guard the input. The input is requested as an non-negative integer.Is there other method to do so? */
/* Operation on DOS window: "PositiveInt1" receives a positive integer only. */
import java.util.*;
public class PositiveInt1{
static int factorial(int n){
int fac=1;
if ((n<0) || (n>12))
return -1;
for (int i=2; i<=n;i++)
fac *=i;
return fac;
}
public static void main(String args[]){
int n=0;
Scanner in = new Scanner(System.in);
while(true){
try{
System.out.println("Input a non-negative integer:");
n = in.nextInt();
}catch(InputMismatchException e){
System.out.println("Your input is mismatched.");
in.next();
continue;
}
if (n<0){
System.out.println("You negative value is not valid.");
continue;
}
break;
}
System.out.printf("Your input is %d\n", factorial(n));
}
}
---------------------
/* via JOpationPane */
import javax.swing.*;
public class PositiveInt{
static class NonNegativeException extends Exception{
public NonNegativeException(String msg){
super(msg);
}
}
static void show(int x)throws NonNegativeException {
if (x<0)
throw new NonNegativeException("Negative integer is not valid.");
}
public static void main(String args[]){
int n=0;
while(true){
try{
String s=JOptionPane.showInputDialog(null,"Input a positive integer:");
n = Integer.parseInt(s);
show(n);
}catch(NumberFormatException e){
System.out.println();
JOptionPane.showMessageDialog( null, "Your input is mismatched. Try again.", "Warning ",JOptionPane.WARNING_MESSAGE);
continue;
}catch(NonNegativeException e){
JOptionPane.showMessageDialog( null, e.getMessage(), "Warning ",JOptionPane.WARNING_MESSAGE);
continue;
}
break;
}
JOptionPane.showMessageDialog(null,"Your input: "+n,"Welcome to DANIWEB", JOptionPane.INFORMATION_MESSAGE);
}
}
tong1 22 Posting Whiz
NormR1 563 Posting Sage Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.