Is there a method to validate whether a user input for an list index is within the list bounds and not a string?

Currently I have a code that looks like this

import java.util.*;
public class Main
{
    
    static Scanner input  = new Scanner(System.in);
    public static void main(String[] args) {
        
        String[] status={"f","f","f","f"};
        System.out.println("Enter index to change: ");
        int userInput  = input.nextInt();
        status[verify(status,userInput)] = "changed";
        System.out.println(Arrays.toString(status));
    }
    
    private static int verify(String statusList[],int userIndex){
        while(userIndex > (statusList.length-1) || userIndex < 0){
            System.out.println("Invalid Index,enter correct Index ");
            userIndex = input.nextInt();
        }
        return userIndex;
    }
}

The “verify” method is used to check whether the user enters an index which is out of Bounds. I am wanting to extend the “verify” method to check if the user enters a string but am not sure how to do that. I want a message to be displayed saying that the user has entered a string and want to keep getting the user input until a correct array index is entered. Is there any way to check whether a string is entered, in the same method?

Answer

Take a look at the following code. Hope it works for you.

Java

import java.util.Arrays;
import java.util.Scanner;

public class Scan {
    
    static Scanner input  = new Scanner(System.in);
    public static void main(String[] args) {
        
        String[] status={"f","f","f","f"};
        System.out.println("Enter index to change: ");
        int userInput  = verify(status, input);
        status[userInput] = "changed";
        System.out.println(Arrays.toString(status));
    }
    
    private static int verify(String statusList[], Scanner input){
        do {
            int userIndex=-1;
         
            String line = input.next();
            try {
                userIndex = Integer.parseInt(line);             
            }catch(NumberFormatException e) {
                System.out.println("Please enter a number.");    
                continue;
            }
            
            if(userIndex > (statusList.length-1) || userIndex < 0){
                System.out.println("Invalid Index,enter correct Index ");   
                continue;
            }else {
                return userIndex;
            }
        }while(true); 
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *