Search code examples
javajcreator

Code for only accepting integers


import javax.swing.*;
import java.awt.*;

public class JCD {

    public static void main(String[] args) {

        String input, inputs;
        int input1, input2;

        input = JOptionPane.showInputDialog("Enter first number");
        inputs = JOptionPane.showInputDialog("Enter second number");

        input1 = Integer.parseInt(input);
        input2 = Integer.parseInt(inputs);

        JOptionPane.showMessageDialog(null, "The GCD of two numbers  " + input
                + "and" + inputs + " is: " + findGCD(input1, input2));

    }// close void

    private static int findGCD(int number1, int number2) {
        // base case
        if (number2 == 0) {
            return number1;

        }// end if

        return findGCD(number2, number1 % number2);
    }// end static

} // close class

What can I add so that it will only accept integers? If not given an integer then it will go back to ask again.....


Solution

  • Put your input request in a while statement, check if it's an int, if not repeat the loop, otherwise exit. Do it for both your inputs.

    Something like this

    public static void main(String[] args) {
    
        String input=null, inputs=null;
        int input1 = 0, input2=0;
    
        boolean err=true;
        do{
            try{
                input = JOptionPane.showInputDialog("Enter first number");
                input1 = Integer.parseInt(input);
                err=false;
            }catch(NumberFormatException e){
                e.printStackTrace();
            }
        }while(err);
    
        err=true;
        do{
            try{
                inputs = JOptionPane.showInputDialog("Enter second number");
                input2 = Integer.parseInt(inputs);
                err=false;
            }catch(NumberFormatException e){
                e.printStackTrace();
            }
        }while(err);
    
        JOptionPane.showMessageDialog(null, "The GCD of two numbers  " + input
                + "and" + inputs + " is: " + findGCD(input1, input2));
    
    }
    

    Note that this solution requires you to initialize your variables when you declare them

        String input = null, inputs = null;
        int input1=0, input2=0;