0

I want to put if () condition to length, So that the user can enter numbers only, if he enters string or char, an error appears.

    System.out.print("Determine the length of array> ");
    int length = input.nextInt();
Omar
  • 1
  • 2
  • 2
    What's wrong with your code as written? – PM 77-1 Aug 27 '21 at 19:00
  • There is no error, but I want to put if() with the condition that it only accepts numbers, what is the syntax should I put in if() to make **length** accept numbers only. – Omar Aug 27 '21 at 19:07
  • 2
    [How to use Scanner to accept only valid int as input](https://stackoverflow.com/q/2912817), [Validating input using java.util.Scanner](https://stackoverflow.com/q/3059333) – Pshemo Aug 27 '21 at 19:11
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 29 '21 at 04:26

3 Answers3

0

You can use Scanner#hasNextInt to guard against invalid input.

if(input.hasNextInt()){
    int length = input.nextInt();
    System.out.println(length);
} else System.out.println("Invalid input");
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

One of the ways you could achieve it is as below:

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Integer val = null;
        try {
            val = scan.nextInt();
            System.out.println(val);
            // do whatever you want to do with your input value
        } catch (Exception exception) {
            System.out.println("you can enter integer only");
            // exit program or log error message
        }
    }
0

You can use java regex,which is only looking numbers

^[0-9]*$ 

So let's check if this is valid,

public static void main(String[] args) {
    boolean valid = false;
    String regexForNumbers = "^[0-9]*$";

    Scanner scanner = new Scanner(System.in);
    while (!valid) {
        System.out.print("Input Value:");
        String s = scanner.nextLine();
        
        if(!s.matches(regexForNumbers)){
           valid= false;
           System.out.println("Not only Numbers, try again\n");
        }else{
            valid = true;
            System.out.println("Only Numbers:"+ s);
        }
    }
}

So what happens is if the user input contains only numbers the execution will end, otherwise, it will keep asking the user to input, and the output of this simple logic will be.

Input Value:maneesha
Not only Numbers, try again

Input Value:maneesha123
Not only Numbers, try again

Input Value:123
Only Numbers:123