I have a 8 digit number that is an int, and would like to know if there is an equivalent method that i could use on it like charAt(). or a way to take just one digit out so that it is still an int value and be able to add, multi, etc.

Hello again Matt.
These follow-on questions could have been added to your original thread, but if you want to start a new thread when the actual question changes perhaps you could take a second to mark the previous threads as solved. Just consider what conclusions people may draw from you having three (or more) questions on the go at once.

charAt returns a char, which is a 16 bit integer (see previous thread). You can add and multiply them to your heart's content. I presume you want to treat the char '0' as a numeric zero (instead of 48), and the char '1' as a numeric one (instead of 49). That's just a matter of subtracting the numeric value of '0' from each char, ie

int n = input.charAt(i) - '0'; // if charAt is '0' n = 0. if charAt is '1' n = 1

Edited 3 Years Ago by JamesCherrill

Hello Matt,

such methods can easily be programmed using standard methods of class String or StringBuilder, respectively.

In below example method figAt() returns the numeric value of a number's figure at position pos. To get the numeric value, the ascii value of '0' must be deducted (as you was already told).

Method figDel() deletes figure at position pos and returns the modified long number. This is based on class StringBuilder which is more flexible to manipulate Strings than String class.

class FigAt {
  public static int figAt(long number, int pos){
    return String.valueOf(number).charAt(pos) - '0';
  }
  public static long figDel(long number, int pos){
    return Long.valueOf(new StringBuilder(String.valueOf(number)).deleteCharAt(pos).toString());
  }
  public static void main(String args[]) {
    long number = 123456789;
    System.out.println("Long number is " + number);
    int i = 7;
    System.out.println("Figure at " + i + " is " + figAt(number, i));
    i = 4;
    System.out.println("Figure at " + i + " deleted " + figDel(number, i));
    /*
      javac FigAt.java
      java FigAt
      Long number is 123456789
      Figure at 7 is 8
      Figure at 4 deleted 12346789
    */
  }
}

Sincerely yours,
1STDAN

This article has been dead for over six months. Start a new discussion instead.