下面的代码应该接受用户的整数,然后以相反的顺序打印他们输入的任何整数。我没有收到任何错误,但是当我运行该程序时,整数不会被反向打印。有人可以帮我找出原因吗?
import java.util.*;
public class ReverseDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String response;
System.out.println("Please enter a whole number.");
response = sc.next();
reverseDigit(response);
}
public static void reverseDigit(String digit) {
ArrayList al = new ArrayList();
al.add(digit);
Collections.reverse(al);
System.out.println("Your number in reverse order is: " + al);
}
}
最佳答案
你误解了 Collections.reverse
做。此方法会反转您提供的列表,而不是其内容。由于您使用具有单个元素的列表调用此方法,因此结果将是相同的列表。
如果要反转字符串,请引用this question .
作为旁注:不要使用像 ArrayList
这样的原始类型,这会遇到麻烦。更喜欢类型安全的方式 ArrayList<String>
。
关于java - Collections.reverse 方法不反转条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33454790/