Check if Input Is Integer

JavaJavaBeginner
Practice Now

Introduction

In Java, there are three methods available to check if the given input is an integer. The first method uses Integer.parseInt() method. The second method uses Scanner.hasNextInt() method. The third method uses Character.isDigit() method. In this lab, we will guide you through all three methods step by step.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/booleans("`Booleans`") java/BasicSyntaxGroup -.-> java/break_continue("`Break/Continue`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117391{{"`Check if Input Is Integer`"}} java/class_methods -.-> lab-117391{{"`Check if Input Is Integer`"}} java/exceptions -.-> lab-117391{{"`Check if Input Is Integer`"}} java/modifiers -.-> lab-117391{{"`Check if Input Is Integer`"}} java/oop -.-> lab-117391{{"`Check if Input Is Integer`"}} java/user_input -.-> lab-117391{{"`Check if Input Is Integer`"}} java/wrapper_classes -.-> lab-117391{{"`Check if Input Is Integer`"}} java/identifier -.-> lab-117391{{"`Check if Input Is Integer`"}} java/arrays -.-> lab-117391{{"`Check if Input Is Integer`"}} java/booleans -.-> lab-117391{{"`Check if Input Is Integer`"}} java/break_continue -.-> lab-117391{{"`Check if Input Is Integer`"}} java/data_types -.-> lab-117391{{"`Check if Input Is Integer`"}} java/for_loop -.-> lab-117391{{"`Check if Input Is Integer`"}} java/if_else -.-> lab-117391{{"`Check if Input Is Integer`"}} java/operators -.-> lab-117391{{"`Check if Input Is Integer`"}} java/output -.-> lab-117391{{"`Check if Input Is Integer`"}} java/strings -.-> lab-117391{{"`Check if Input Is Integer`"}} java/variables -.-> lab-117391{{"`Check if Input Is Integer`"}} java/string_methods -.-> lab-117391{{"`Check if Input Is Integer`"}} java/system_methods -.-> lab-117391{{"`Check if Input Is Integer`"}} end

Create a Java file

First, open the terminal on Ubuntu system and create a Java file using the following command:

touch ~/project/CheckInputInteger.java

Checking valid integer using Integer.parseInt() method

  1. Create a function named checkValidIntegerUsingIntegerParseIntMethod().
  2. In the function, use the Integer.parseInt() method to parse a string to integer.
  3. Use the try-catch block to handle the exception that is thrown if the input is not a valid integer.
  4. If the parsing is successful, print a message indicating that the given input is a valid integer.
  5. If the parsing is unsuccessful, print a message indicating that the given input is not a valid integer.
  6. Add code comments to the code block.
public static void checkValidIntegerUsingIntegerParseIntMethod() {
        String input = "1234";
        try {
            Integer.parseInt(input);
            System.out.println(input + " is a valid integer");
        } catch (NumberFormatException e) {
            System.out.println(input + " is not a valid integer");
        }
}
  1. Call the function in the main method.
public static void main(String[] args) {
        checkValidIntegerUsingIntegerParseIntMethod();
}

Checking valid integer using Scanner.hasNextInt() method

  1. Create a function named checkValidIntegerUsingScannerHasNextIntMethod().
  2. In the function, use Scanner.hasNextInt() method to check whether the given input is an integer or not.
  3. Print a message indicating that the given input is a valid integer if the input is an integer, otherwise print a message indicating that the given input is not a valid integer.
  4. Add code comments to the code block.
public static void checkValidIntegerUsingScannerHasNextIntMethod() {
        Scanner sc = new Scanner(System.in);
        if(sc.hasNextInt()) {
            System.out.println(sc.nextInt()+" is valid Integer");
        } else {
            System.out.println(sc.nextInt()+" is valid Integer");
        }
        sc.close();
}
  1. Call the function in the main method.
public static void main(String[] args) {
        checkValidIntegerUsingScannerHasNextIntMethod();
}

Checking valid integer using Character.isDigit() method

  1. Create a function named checkValidIntegerUsingCharacterIsDigitMethod().
  2. In the function, use Character.isDigit() method to check each character of the input string to see if it is a digit or not.
  3. If all characters in the string are digits, print a message indicating that the given input is a valid integer.
  4. If non-digit characters exist, print a message indicating that the given input is not a valid integer.
  5. Add code comments to the code block.
public static void checkValidIntegerUsingCharacterIsDigitMethod() {
        String input = "1234";
        Boolean flag=true;
        for(int a=0; a<input.length(); a++) {
            if(a==0 && input.charAt(a) == '-')
                continue;
            if( !Character.isDigit(input.charAt(a)))
                flag=false;
        }
        if(flag) {
            System.out.println(input+" is valid Integer");
        }
   }
  1. Call the function in the main method.
public static void main(String[] args) {
        checkValidIntegerUsingCharacterIsDigitMethod();
}

Summary

In this lab, we learned to use the available methods to check if the given input is an integer or not. We used Integer.parseInt() method, Scanner.hasNextInt() method, and Character.isDigit() method to check if the given input is an integer. We created Java code blocks and added code comments to them. Finally, we ran the code in the terminal of Ubuntu system.

Other Java Tutorials you may like