Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Steven Bell
660 PointsFour-Digit Integer
Write a program that reads a four-digit integer, such as 1998, and then displays it, one digit per line, like so: 1 9 9 8 Your prompt should tell the user to enter a four-digit integer. You can then assume that the user follows directions. (Hint: Use the division and remainder operators.)
Steven Bell
660 Points1 /n, 9/n, 9/n, 8/n
1 Answer
Kourosh Raeen
23,733 PointsHi Steven - Using the modulus or remainder operator you can get the right-most digit. For example, 1998%10 will give you 8. Then if you divide 1998 by 10 you will get 199 and now you can apply the modulus operator again to get 9. Using this approach you will get the digits, but in reverse order. One thing you could do to print them in the right order is to put digits in a stack and then when you pop them off the stack you'll get them in the right order. Here's the code:
import java.util.Scanner;
import java.util.LinkedList;
public class PrintDigitsStack {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a four digit number: ");
int num = reader.nextInt();
LinkedList<Integer> stack = new LinkedList<Integer>();
while (num > 0) {
stack.push(num%10);
num /= 10;
}
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
I also saw another way of doing this using recursion which eliminates the need for the stack. Here's the code for that:
import java.util.Scanner;
public class PrintDigitsRecursive {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a four digit number: ");
int num = reader.nextInt();
printDigits(num);
}
public static void printDigits(int num) {
if(num / 10 > 0) {
printDigits(num / 10);
}
System.out.println(num % 10);
}
}
Steven Bell
660 PointsSteven Bell
660 PointsI'm sorry! It should print out like: 1 9 9 8