183k views
2 votes
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.

User Shiva Garg
by
4.1k points

1 Answer

5 votes

Answer:

import java.util.*;

class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

String str = sc.nextLine();

System.out.print("You have entered: " + str + "\\");

Stack stk = new Stack();

for (int i = 0; i < str.length(); i++) {

stk.push(str.charAt(i));

}

String reversed = "";

while(!stk.empty()) {

reversed += stk.pop();

}

System.out.print("Reversed this is: " + reversed + "\\");

}

}

Step-by-step explanation:

This solution works for all types of input of all lengths.

If needed you could rework it for just integers.

User Malificent
by
4.4k points