0

I'm trying to convert a string filled with 16 digits into an array of ints where each index holds the digit of its respective index in the string. I'm writing a program where I need to do math on individual ints in the string, but all of the methods I've tried don't seem to work. I can't split by a character, either, because the user is inputting the number.

Here's what I have tried.

//Directly converting from char to int 
//(returns different values like 49 instead of 1?)    
//I also tried converting to an array of char, which worked, 
//but then when I converted
//the array of char to an array of ints, it still gave me weird numbers.

for (int count = 0; count <=15; count++)
{
   intArray[count] = UserInput.charAt(count);
}

//Converting the string to an int and then using division to grab each digit,
//but it throws the following error (perhaps it's too long?):
// "java.lang.NumberFormatException: For input string: "1234567890123456""

int varX = Integer.parseInt(UserInput);
int varY = 1;
for (count=0; count<=15; count++)
{
    intArray[count]= (varX / varY * 10);
}

Any idea what I should do?

2
  • 1
    Yes, that number (1234567890123456) is too big for an int, which has a max value of (2^32-1) Commented May 13, 2012 at 11:33
  • Delete the question if you think it should be, don't edit it with a thousand x'es... Other users might find useful information in the original question, even if it is stupid. Commented May 14, 2012 at 19:40

2 Answers 2

5

how about this:

for (int count = 0; count < userInput.length; ++count)
   intArray[count] = userInput.charAt(count)-'0';
Sign up to request clarification or add additional context in comments.

2 Comments

That worked perfectly! Thank you so much :) Can I ask what the changes did? I noticed you changed it to ++count and added - '0' to the end.
the "++" is a super tiny performance tip that came from the C++ days , i think java compiler is good enough to recognize it can optimize it too . the '0' makes it easier to understand how to convert from a char to a number , since '0'-'0' ==0 , '1'-'0'==1 , and so on ...
-1

I think that the thing that is a bit confusing here is that ints and chars can be interpited as eachother. The int value for the character '1' is actually 49.

Here is a solution:

for (int i = 0; i < 16; i++) {
    intArray[i] = Integer.valueOf(userInput.substring(i, i + 1));
}

The substring method returns a part of the string as another string, not a character, and this can be parsed to an int.

Some tips:

  • I changed <= 15 to < 16. This is the convetion and will tell you how many loop interations you will actually go throug (16)
  • I changed "count" to "i". Another convention...

1 Comment

Thanks for that explanation :) I am very bad with conventions ;( I appreciate the suggestions and I will try to be more conventional from now on!

Your Answer

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