How to use something like the charAt for integers

Connor Marchand picture Connor Marchand · Sep 29, 2015 · Viewed 13.3k times · Source

I am trying to make a program that uses three digit numbers to identify items and I am trying to use something like the charAt method for integers or something. Im not too sure. Im a beginner and I apologize i just need help. Also I need a bit of help to use an if statement and relational operators. Im trying to do if the last digit in the number is less than 5 then it is {item} and if its greater than 5 then its this {item}. Something like that. Thank you so much in advance.

    String number;

    System.out.println("Enter three digit number: ");
    number = in.nextLine();

    switch (number.charAt(0))
    {
         //stuff
    }

    if (number > 5)
    {
      //it is this item
    {
    else
    {
      //it is the other item
    {

Answer

Lu Li picture Lu Li · Sep 30, 2015

There are at least two ways you can do it:

  1. String number = in.nextLine();
    char c = number.charAt(i); // i is the position of digit you want to retrieve
    int digit = c - '0';
    
  2. if you want to get ith digit from the end of an Integer, do:

    int digit = 0;
    while(i > 0) {
        digit = n%10;
        n /= 10;
        --i;
    }