1

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

2 Answers 2

3
  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'}; 
Sign up to request clarification or add additional context in comments.

1 Comment

that would be the problem. Thank you for your help
1

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 "'".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.