Collections.reverse方法没有倒车进入 [英] Collections.reverse method not reversing entry

查看:572
本文介绍了Collections.reverse方法没有倒车进入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面code被认为能接受来自用户的一个整数,然后打印它们以相反的顺序输入任何整数。我越来越没有错误,但是当我运行这个程序并没有被打印在背面的整数。是否有人可以帮助我弄清楚为什么?

 进口的java.util。*;公共类ReverseDigits {    公共静态无效的主要(字串[] args){
        扫描仪SC =新的扫描仪(System.in);
        字符串响应;        的System.out.println(请输入一个整数。);
        响应= sc.next();        reverseDigit(响应);
    }    公共静态无效reverseDigit(字符串的数字){
        ArrayList的人=新的ArrayList();
        al.add(数字);
        Collections.reverse(人);
        的System.out.println(您以相反的顺序号为:+人);
    }}


解决方案

您misinter preTED什么的 Col​​lections.reverse 一样。这种方法颠倒,你给的列表中,的的内容。既然你调用此方法具有单个元素的列表,其结果将是相同的列表。

如果要反转的字符串,请参阅这个问题

作为一个侧面说明:不要使用原始类型,如的ArrayList ,这会惹上麻烦。 preFER类型安全方式的ArrayList<串GT;

My code below is supposed to accept an integer from the user, and then print whatever integer they enter in reverse order. I am getting no errors, but when I run this program the integer is not being printed in reverse. Can someone please help me figure out why?

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);
    }

}

解决方案

You misinterpreted what Collections.reverse does. This method reverses the list that you gave, not its content. Since you called this method with a list having a single element, the result will be the same list.

If you want to reverse a String, please refer to this question.

As a side-note: do not use raw types like ArrayList, this will get into trouble. Prefer the type-safe way ArrayList<String>.

这篇关于Collections.reverse方法没有倒车进入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆