我的程序应该采用随机整数并反转它们.它目前适用于长度不超过十位的所有正整数.
import java.util.Scanner; public class Program2 { public static void main(String[] args) { // TODO Auto-generated method stub int input; Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); input = scanner.nextInt(); System.out.print("Its reversal is "); reverse(input); System.out.println();; } public static void reverse(int number) { if(number < 10 && number > 0) { System.out.println(number); return; } else { System.out.print(number % 10); reverse(number/10); } } }
我一直无法找到让程序返回负数反转的方法.最简单的方法是什么?
根据上面的评论,看起来你想要反转-123为-321.如果是这样,我认为这段代码应该有效:
public static void reverse(int number) { if (number < 0) { System.out.print("-"); reverse(number * -1); } else if (number < 10) { System.out.println(number); } else { System.out.print(number % 10); reverse(number / 10); } }
(我放弃了,&& number > 0
因为如果输入完全正确,你会有一个无限循环0
.)
注意:此代码将给出一个StackOverflowError
for number == Integer.MIN_VALUE
,因为-Integer.MIN_VALUE == Integer.MIN_VALUE
.您可以按如下方式解决此问题:
if (number < 0) { System.out.print("-"); if (number == Integer.MIN_VALUE) { System.out.print(-(number % 10)); number /= 10; } reverse(-number); } else if ...