What is the nextInt() Method in Java?
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
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
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
and1
. - In base-8 (octal), valid characters range from
0
to7
. - In base-16 (hexadecimal), valid characters are
0-9
andA-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.
GO TO FULL VERSION