-2

What is the likely reason for a compilation error in this code?

public class Reverse {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        int ans = 0;

        while (num > 0) {
            int rem = num % 10;
            num = num / 10;
            ans = ans * 10 + rem;
        }

        System.out.println(ans);
    }
}

I want to be able to input values using the keyboard.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Naza
  • 1
  • 1
  • 6
    Compilers are usually quite explicit about what causes a compilation error – UnholySheep May 30 '23 at 14:16
  • Hint: next time show us the compilation error. Or better still, *read* the compilation error and see if you can figure out what it means yourself. Hint #2: Googling for a compilation error that you don't understand is often helpful; e.g. https://stackoverflow.com/questions/25706216 – Stephen C May 30 '23 at 14:43

2 Answers2

1

You're obviously working with standard console input/output. So you need to tell JVM you want console input to be used in your project.

Every class you use in your projects must be described either in your code OR imported from somewhere else.

Here, you used standard class Scanner but didn't imported it. Do so by typing import java.util.Scanner; before you use it.

0

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();
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132