-2

what i want to do is take a String of numbers like "8675309" and then do some math based on different digits from the String. i'd be happy to get 8, 6, 7, 5, 3, 0, 9 and then using the indexes, but they seem to give weird numbers (like 51) so far. i simply want to wind up doing myArray[0] + myArray[3] = output (this example would be 8+5=13)

i own 6 books on Java and none of them cover this. 6+ hours on the web (google, stackoverflow, youtube, others) and nowhere can i find this. - no matter how i search i get results of everything but.

from arrays which are already populated, to strings already delimited, to discarding everything but numbers from a string, etc...

i tried using/modifying what i've found and the best i can come up with has eclipse yelling at me that it's not possible to convert a char to an int.

    String str = cn;
    char[] charArray = str.toCharArray(); 

    String number = String.valueOf(cn);
    int[] digits1 = number.toCharArray();

    int newInt = charArray[0];  
    System.out.println(newInt);

"Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from char[] to int[]"

codeNewb
  • 1
  • 1

2 Answers2

2

You can convert a single char representing a decimal digit to an int by calling Character.digit(myChar, 10). Call this method in a loop for the results obtained from toCharArray() to construct your desired array of ints:

String str = cn;
char[] charArray = str.toCharArray(); 
int[] digits = new int[charArray.length()];
for (int i = 0 ; i != digits.length() ; i++) {
    digits[i] = Character.digit(charArray[i], 10);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You can get individual digits from such a string by converting it into an array of characters and then parsing each of those characters into a digit.

    String text = "8675309";
    char[] characters = text.toCharArray();
    List<Integer> digits = new ArrayList<>();

    for(char character : characters) {
        digits.add(Character.getNumericValue(character));
    }

You can access each of the digits by iterating through the list.

Ashray Mehta
  • 375
  • 1
  • 7