目录
*18.8 (以逆序输出一个整数中的數字)
编写一个递归方法,使用下面的方法头在控制台上以逆序显示一个 int 型的值:
public static void reverseDisplay(int value)
例如,reverseDisplay(12345)显示的是54321。编写一个测试程序,提示用户输入一个整数 . 然后显示它的逆序数字。
-
代码示例
编程练习题18_8ReverseOrderOutput.java
package chapter_18;
import java.util.Scanner;
public class 编程练习题18_8ReverseOrderOutput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a integer: ");
int n = input.nextInt();
reverseDisplay(n);
input.close();
}
public static void reverseDisplay(int value) {
if(value >= 10) {
int n = value%10;
System.out.print(n);
reverseDisplay(value/=10);
}else
System.out.print(value);
}
}
-
输出结果
Enter a integer: 12345
54321