如何将整数转为字符串后实现字符串反转?
Hey there! Let's walk through fixing your code to properly reverse the string representation of an input integer. First, let's break down the clear issues in your current code:
- Variable Name Mismatch: You defined
strNumbut tried to passs1(a variable that doesn't exist yet) to thereversemethod. - Parameter Type Mismatch: Your
reversemethod accepts anint, but you're trying to pass aStringto it—this will cause a compile error. - Incorrect Return Value: The
reversemethod prints characters directly inside the method and returns0instead of the actual reversed result, so your main method ends up printing0instead of the reversed string.
Here are a few polished, working solutions to achieve your goal, with explanations for each approach:
Approach 1: Return the Reversed String (Simplest)
This method converts the integer to a string, reverses it using Java's built-in StringBuilder tool (optimized for string manipulations), and returns the reversed string:
import java.util.Scanner; public class Lab7 { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Type the integer you'd like to be reversed:"); int num = s.nextInt(); // Get reversed string and print it String reversedResult = reverseToString(num); System.out.println("Reversed result: " + reversedResult); s.close(); // Clean up the scanner resource } // Takes an int, returns its reversed string representation public static String reverseToString(int num) { String strNum = Integer.toString(num); return new StringBuilder(strNum).reverse().toString(); } }
Approach 2: Return the Reversed Integer (With Edge Case Handling)
If you want to output a reversed integer instead of a string (and handle negative numbers properly), use this version—it also adds error handling for cases where reversing the number would cause an integer overflow:
import java.util.Scanner; public class Lab7 { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Type the integer you'd like to be reversed:"); int num = s.nextInt(); try { int reversedNum = reverseToInt(num); System.out.println("Reversed integer: " + reversedNum); } catch (NumberFormatException e) { System.out.println("Oops! The reversed number is too large to fit in an integer."); } s.close(); } public static int reverseToInt(int num) { String strNum = Integer.toString(num); StringBuilder reversedBuilder = new StringBuilder(strNum); // Keep the negative sign at the start for negative numbers if (num < 0) { reversedBuilder.deleteCharAt(0); reversedBuilder.reverse(); reversedBuilder.insert(0, '-'); } else { reversedBuilder.reverse(); } return Integer.parseInt(reversedBuilder.toString()); } }
Approach 3: Manual Loop (Matching Your Original Style)
If you prefer to use a manual loop like your initial attempt, here's how to adjust it to return the reversed string instead of printing inside the method:
public static String reverseWithLoop(int num) { String strNum = Integer.toString(num); StringBuilder reversed = new StringBuilder(); for (int i = strNum.length() - 1; i >= 0; i--) { reversed.append(strNum.charAt(i)); } return reversed.toString(); }
Key Improvements Across All Versions:
- Fixed variable and parameter type mismatches so the code compiles without errors.
- Avoided direct printing inside helper methods—instead, we return results to keep code modular.
- Added scanner cleanup to prevent resource leaks.
- Handled edge cases like negative numbers and integer overflow.
内容的提问来源于stack exchange,提问作者Harley Jenkins

