You code works fine as-is. The only thing that looks wrong is the lack of imported classes.
Here is a version of your code where the Scanner
class is imported and the algorithm exists in its own static method. I added method called reversedNumberAsString
to verify if the computed value is correct.
Note: When requesting input, you should typically display a prompt to let the user know the program is awaiting input.
import java.util.Scanner; // Import the Scanner class from the java.util package
public class ReverseInteger {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Open scanner
System.out.print("Enter a number: "); // Prompt user
int num = input.nextInt(), ans = reverse(num); // Grab input and compute
input.close(); // Close scanner
String expected = reversedNumberAsString(num); // Expected reversed
String actual = Integer.toString(ans, 10); // Computed number as string
System.out.println(ans); // Display the reversed number
System.out.printf("Correct?: %b", actual.equals(expected)); // Correct?
}
// Algorithm as its own function
public static int reverse(int num) {
int ans = 0;
while (num > 0) {
int rem = num % 10;
num = num / 10;
ans = ans * 10 + rem;
}
return ans;
}
private static String reversedNumberAsString(int num) {
return new StringBuilder(Integer.toString(num, 10)).reverse().toString();
}
}