java - 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 2 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 add accept integers? if not given integer go ask again.....

put input request in while statement, check if it's int, if not repeat loop, otherwise exit. both inputs.

something 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 2 numbers  " + input             + "and" + inputs + " is: " + findgcd(input1, input2));  } 

note solution requires initialize variables when declare them

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

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -