2

In java when I was working on Netbeans Ide I saw method of nextInt(int radix). I tried to implement this and passed an integer number, but that gave an exception of InputMismatchException. My code is as follows:

import java.util.*;
import java.lang.*;
public class HelloWorld{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(2);
System.out.println(n);
}

I want know that what is radix argument? Also,what is its use?

Asheesh Sahu
  • 342
  • 2
  • 12

1 Answers1

6

The radix is the base in which the number will be interpreted. You can use it to make the nextInt method interpret the number as non-decimal.

For example, the following expects a number in binary:

s.nextInt(2)
> 11111 //input
31 //result in decimal

And this expects a hex number:

s.nextInt(16)
> abc12 //input
703506 //result in decimal

You'll also be interested to see other methods using a radix, such as Integer.toString(int, int), Integer.parseInt(String, int), which format/parse numbers in a specified radix (similar methods are provided by Long, Short, etc)

ernest_k
  • 44,416
  • 5
  • 53
  • 99