Reputation:
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
Upvotes: 0
Views: 164
Reputation: 45
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);
}
}
Upvotes: 1
Reputation: 262684
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));
Upvotes: 2
Reputation: 726809
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);
}
Upvotes: 4