In: Computer Science
Write a java program that uses a stack to reverse an integer of
three digits. The program must prompt the user to input an integer
of 3 digits and display it in reverse.
- Your program must include the Stack class, the Reverse class, and
the Test class.
- In the Test class, the program must prompt the user to input a
3-digit number and display it in reverse.
- Class Reverse must use the Stack class to reverse the
number.
Note: the input must be of type integer.
Here is a sample run:
Enter a 3-digit integer: 123
The reversed number: 321
Here is the complete java code with comments:
NOTE: Not only it works for 3 digits, but for even more number of digits :)
//To get input
import java.util.*;
//To use power function
import java.lang.Math;
//This is the stack class
class StackClass {
// This arraylist will work as a stack
public ArrayList<Integer> mystack = new ArrayList<Integer>();
// This will add to the stack till the number becomes 0
public StackClass(int n) {
while (n != 0) {
mystack.add(n % 10);
n = n / 10;
}
}
}
// Reverse Class
class Reverse {
int reversedNum;
Reverse(StackClass st) {
reversedNum = 0;
for (int i = 0; i < st.mystack.size(); i++) {
/*
* The numeber gets converted like this: If the number is 3 2 1 in the stack
* then it will be converted like this revNum = 3*(100) + 2*(10) + 1(1) = 321
* which is reverse of 123
*/
reversedNum = (int) (reversedNum + st.mystack.get(i) * (Math.pow(10, st.mystack.size() - i - 1)));
}
}
}
public class Test {
// This is the main function
public static void main(String[] args) {
// The scanner is used to take the input
Scanner sc = new Scanner(System.in);
System.out.print("Enter a 3 digit number: ");
int n = sc.nextInt();
StackClass stobj = new StackClass(n);
Reverse obj = new Reverse(stobj);
System.out.println("The reversed number: " + obj.reversedNum);
sc.close();
}
}
Here is the output for the above code: