How do I fix the error validating int java?

I need the user to enter a number as a string but i need to validate it as an int to make sure it is between 1-7 inclusive.

static void editPrivateContract()//menu choice 3
    {
        int num = 0;
        String msg;

        msg = " Please enter the number of the Private Contract contract to be edited \t: ";
        num = validateInt(msg, 1, privateContractArrayCount);//validating the range of Contracts

        privateContractArray[num - 1].displayNumDetails();// for the 0 based array

        msg = " \n\nWhich credentials would you like to edit...1-8 \t: ";

        int reply = validateInt(msg, 1, 8); //user must select between 1 and 7

2 answers

  • answered 2020-03-25 13:46 RR_IL

    Guess something like this can work

    static boolean validateInt(String message,int rangeStart,int rangeEnd)
     {
    
         int tmp = 0;
         for(int i = 0 ; i < message.length(); i++ )
         {  
             tmp = (message.charAt(i) - '0');
             if( tmp < rangeStart || tmp > rangeEnd)
                 return false;
         }
         return true;
     }
    
     public static void main(String [] args)
     {   
         System.out.println(validateInt("1237",1,3)); 
         System.out.println(validateInt("123",1,3)) ; 
         System.out.println(validateInt("123",2,3)) ; 
     }
    

    Output

    false
    true
    false
    

    You can also use Integer.parseInt

     static boolean validateInt2(String message,int rangeStart,int rangeEnd)
     {
         int tmp = 0;
         try{ 
             tmp = Integer.parseInt(message);
         }catch(NumberFormatException parseIntException){
             return false;
         }
         return (tmp > rangeStart && tmp < rangeEnd);
     }
    

  • answered 2020-03-25 14:10 WJS

    You didn't provide much information but here is one way of doing it. It reads an int from the console. It could also read in a string.

            Scanner sc = new Scanner(System.in);
            String msg = " \n\nWhich credentials would you like to edit...1-8 \t: ";
            int reply = validateInt(sc, msg, 1, 8); // user must select between 1 and 7
    
    
        public static int validateInt(Scanner sc, String msg, int min, int max) {
            int num = 0;
            while (num < min || num > max) {
                System.out.print(msg);
                num = sc.nextInt();
            }
            return num;
        }