简体   繁体   中英

How can i get an index of a string as an int?

I create an integer and I have to print out the values backwards. So if my number is 12345, it has to print:

5
4
3
2
1

The numbers have to be on a separate line:

System.out.println(number.nextDigit());

Each with a method nextDigit(); which returns the next number from the last and it must return an integer not a char or a string.

Any help?

Here is my code: http://pastebin.com/xrpKZixE

Unlike strings that may consist of multiple characters, int s represent a single number.

The trick to solving this problem with int s is applying % and / operators: by taking num % 10 , you get the last digit; by taking num / 10 , you chop the last digit off.

while (num != 0) {
    int lastDigit = num % 10;
    num /= 10;
    System.out.println(lastDigit);
}

Probably easiest to convert to a String, and go from there:

String digits = String.valueOf(number);
char thirdDigit = digits.charAt(2);
int thirdDigitAsNumber = Integer.parseInt(digits.substring(2,3));

The above answers are good. If I understand your question correctly you can also use recursive method to print your numbers verticaly starting from last digit here is the recursive method that you can use:

public static void writeVertical(int number)
{
if(number <10)
 System.out.println(number);
else
{
 System.out.println(number%10);
 writeVertical(number/10);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM