What is the nextInt() Method in Java?

The nextInt() method scans the next token of the input data as an “int”.
As the name of the class Scanner elaborates, nextInt() method of this class is used to scan or parse the input in Java. The input can be stored either as String, read from a file, real-time data or any System input by the user. This completely depends on the nature and need of your program. Please note that you need to import java.util.Scanner; before using the scanner object.

Scanner nextInt() method Example 1

Let’s take our first dive to the basic example.

import java.util.Scanner;

public class TestIntInput {

	public static void checkInt(String testData) {

		System.out.println(testData);

		Scanner scanner = new Scanner(testData);

		while (scanner.hasNext()) {

			if (scanner.hasNextInt()) {
				// calling the nextInt() method
				System.out.println(scanner.nextInt() + "\t\t INT FOUND!");
			} else {
				System.out.println(scanner.next() + "\t\t");
			}
		}
		scanner.close();
		System.out.println();
	}

	public static void main(String[] args) {

		String testData1 = "My 3 years old cat Diana, just gave birth to 5 healthy babies.";
		String testData2 = "The number 1 place to learn Java is CodeGym!";
		String testData3 = "6; 5 4 3. 2 1 !";
		
		checkInt(testData1);
		checkInt(testData2);
		checkInt(testData3);

	}
}

Output

My 3 years old cat Diana, just gave birth to 5 healthy babies. My 3 INT FOUND! years old cat Diana, just gave birth to 5 INT FOUND! healthy babies. The number 1 place to learn Java is CodeGym! The number 1 INT FOUND! place to learn Java is CodeGym! 6; 5 4 3. 2 1 ! 6; 5 INT FOUND! 4 INT FOUND! 3. 2 INT FOUND! 1 INT FOUND! !

Explanation

One thing to note in the above example in testData3 is that a number needs to be space-separated to be scanned as an individual int. That’s the reason why 6 and 3 are not identified as integers because they are colon and comma-separated respectively.

Scanner nextInt() method Example 2

This example uses the System input to scan it as integers.

import java.util.Scanner;

public class TestSystemInput {

	public static void getFinalExamScore() {
		
		System.out.println("Get Your Final Exam Score!\n");

		int finalScore = 0;
		int totalCourses = 0;
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter total Courses: ");
		totalCourses = scanner.nextInt();

		for (int i = 0; i < totalCourses; i++) {
			System.out.println("Enter score in course " + (i + 1) + " : ");
			finalScore = finalScore + scanner.nextInt();
		}

		System.out.println("Your final Score = " + finalScore);
		scanner.close();
	}

	public static void main(String[] args) {

		getFinalExamScore();
	}
}

Output

Get Your Final Exam Score! Enter total Courses: 3 Enter score in course 1 : 10 Enter score in course 2 : 15 Enter score in course 3 : 15 Your final Score = 40

What is the 'Radix' Parameter?

The radix parameter specifies the base (or radix) in which the input number is represented. By default, nextInt() assumes a base-10 (decimal) number system. However, you can use the radix parameter to parse numbers in other bases, such as binary (base-2), octal (base-8), or hexadecimal (base-16).

Syntax of nextInt() with Radix


int number = scanner.nextInt(radix);

Here, radix is an integer representing the base in which the input number is expressed. Valid values for radix range from 2 to 36.

Examples of Using nextInt() with Radix

Example 1: Parsing a Binary Number


import java.util.Scanner;

public class RadixExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a binary number: ");
        int binaryNumber = scanner.nextInt(2); // Specify radix 2 for binary

        System.out.println("Decimal equivalent: " + binaryNumber);
    }
}

Input: 1011

Output: Decimal equivalent: 11

In this example, the input 1011 is interpreted as a binary number and converted to its decimal equivalent, 11.

Example 2: Parsing an Octal Number


import java.util.Scanner;

public class RadixExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an octal number: ");
        int octalNumber = scanner.nextInt(8); // Specify radix 8 for octal

        System.out.println("Decimal equivalent: " + octalNumber);
    }
}

Input: 17

Output: Decimal equivalent: 15

Here, the input 17 is treated as an octal number and converted to its decimal equivalent, 15.

Example 3: Parsing a Hexadecimal Number


import java.util.Scanner;

public class RadixExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a hexadecimal number: ");
        int hexNumber = scanner.nextInt(16); // Specify radix 16 for hexadecimal

        System.out.println("Decimal equivalent: " + hexNumber);
    }
}

Input: A3

Output: Decimal equivalent: 163

In this case, the input A3 is interpreted as a hexadecimal number and converted to its decimal equivalent, 163.

Error Handling with nextInt(radix)

When using the radix parameter, it's important to ensure that the input string is valid for the specified base. For instance:

  • In base-2 (binary), valid characters are 0 and 1.
  • In base-8 (octal), valid characters range from 0 to 7.
  • In base-16 (hexadecimal), valid characters are 0-9 and A-F (case-insensitive).

If the input contains invalid characters for the specified base, a InputMismatchException will be thrown.

Example: Handling Invalid Input


import java.util.Scanner;

public class RadixExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("Enter a binary number: ");
            int binaryNumber = scanner.nextInt(2); // Specify radix 2 for binary

            System.out.println("Decimal equivalent: " + binaryNumber);
        } catch (Exception e) {
            System.out.println("Invalid input! Please enter a valid binary number.");
        }
    }
}

This approach ensures that your program remains robust and user-friendly, even when invalid input is provided.

Practical Applications of nextInt(radix)

  • Data Parsing: Convert numbers from different numeral systems for calculations.
  • User Input Validation: Ensure input adheres to a specific numeral system.
  • Learning Tools: Teach concepts of numeral systems by dynamically converting inputs.

Conclusion

That’s a wrap for the nextInt() method by Scanner class in Java. It can be a little overwhelming at first but practise will keep you afloat. Feel free to hop on in case of any ambiguity. We encourage you to play around with different input methods for a better understanding. Happy learning!