nfoggia
nfoggia

Reputation: 513

Java: converting char arrays to int

so i am trying to convert an array of 3 characters to an integer. Here is what i have so far:

   char[] characters = {0, 1, 2}; 
   int number = Integer.parseInt(new String(characters));
   System.out.println(number);

however this prints the error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "�"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:481)
    at java.lang.Integer.parseInt(Integer.java:527)
    at usemyinteger.UseMyInteger.main(UseMyInteger.java:41)

Java Result: 1

Upvotes: 1

Views: 8461

Answers (2)

Liubing
Liubing

Reputation: 51

For your good, please add 2 lines to print tmp string, it will help you to find real problem.

char[] characters = {0, 1, 2};
String tmp=new String(characters);
System.out.println("tmp = " + tmp);
int number = Integer.parseInt(tmp);
System.out.println(number);

And you will see tmp is unreadable string, now you should know you missed "'".

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122026

  char[] characters = {0, 1, 2}; 

Because now 0 1 2 are the integer literals , taking as the ASCII code for the character's .Not the actual characters '0' '1' '2'

should be

  char[] characters = {'0', '1', '2'}; 

Upvotes: 3

Related Questions