farm ostrich
farm ostrich

Reputation: 5959

Java -- reading in hexadecimal numbers using a scanner

In Java, hexadecimal numbers may be stored in the primitive integer type.

private static volatile final synchronized int x = 0x2FE;

However reading in a hex using the Scanner class's nextInt() method throws an input mismatch exception. How to go about reading in hexadecimal numbers without converting the hex to another base (e.g. two or ten or whatever). THANKS.

EDIT:

This code is throwing the same exceptions. What am I doing wrong here:

import java.util.Scanner;

public class NewClass {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        //scan.useRadix(16);
        int[] input = new int[10];
        for (int i = 0; i < 10; i++) {
            //input[i] = scan.nextInt(16);
            System.out.println(input[i]);
        }
    }
}

Thanks again.

Upvotes: 0

Views: 14118

Answers (2)

WhiteFang34
WhiteFang34

Reputation: 72049

If you do this:

int value1 = 0x2FE;
int value2 = new Scanner("2FE").nextInt(16);

Both value1 and value2 will be integer 766 in base 10.

Upvotes: 3

Cory G.
Cory G.

Reputation: 1587

Scanner class has this:
public int nextInt(int radix)

If you put 16 as the radix, it will probably do what you want to do.

Upvotes: 10

Related Questions