chubakur
chubakur

Reputation: 51

Scanner for specified string does not work

            String si = "asd";
            Scanner sc = new Scanner(si);
            byte d = sc.nextByte();

In the documentation about Scanner(String string) constructor: Constructs a new Scanner that produces values scanned from the specified string.

This code is crushes with InputMismatchException. What I doing wrong?

Upvotes: 1

Views: 88

Answers (3)

Christian Tapia
Christian Tapia

Reputation: 34146

First, is important to know that the range of a byte in Java is [-128, 127].

Now, according to Java Docs, the nextByte() method (emphasis mine):

Throws: InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

So, it expects to read a number in the range [-128, 127] from the String. Otherwise, it will throw that exception.

An example of how can you use it would be:

String si = "-128";
Scanner sc = new Scanner(si);
byte d = sc.nextByte();
System.out.println(d); // -128

Edit: One simple solution to access to the characters of an String would be to convert it into an array char[]:

char[] chars = si.toCharArray();
System.out.println(chars[index]);

Upvotes: 2

Dariusz
Dariusz

Reputation: 371

Check JavaDoc for nextByte method. You are trying to read a byte from a string that does not contain any numbers.

Upvotes: 0

BackSlash
BackSlash

Reputation: 22233

Scanner.nextByte() reads the next available byte in the string. byte is a numerical value, and as you can see your string only contains characters.

In fact if you try with:

String si = "-20 asd";
Scanner sc = new Scanner(si);
byte d = sc.nextByte();

It will work, because -20 is an acceptable byte, and after the last line d will hold -20.

If you want to get the byte representation of your string, just do

byte[] bytes = sc.next().getBytes();

or even

byte[] bytes = si.getBytes();

Upvotes: 3

Related Questions