0

我尝试在没有任何 for 循环的情况下打印输入数字的反向。但是我在打印 Arraylist 时遇到了一些问题。如何将 Arraylist [3, 5, 4, 1] 打印为 3541 - 不带括号、逗号和空格?

如果不可能,如何将我的 ArrayList 元素添加到 stringlist 然后打印?

public static void main(String[] args) {

    int yil, bolum = 0, kalan;
    Scanner klavye = new Scanner(System.in);
    ArrayList liste = new ArrayList();
    //String listeStr = new String();
    System.out.println("Yıl Girin: "); // enter the 1453
    yil = klavye.nextInt();

    do{ // process makes 1453 separate then write in the arraylist like that [3, 5, 4,1]

        kalan = yil % 10;
        liste.add(kalan);
        bolum = yil / 10;
        yil = bolum;

    }while( bolum != 0 );

    System.out.println("Sayının Tersi: " + ....); //reverse of the 1453
    klavye.close();
}
4

4 回答 4

3
  • 将条目作为字符串读取
  • 反转它String reverse = new StringBuilder(input).reverse().toString();
  • 可选:如果您需要使用该 int 进行一些计算,请将其解析为 int。
于 2012-10-22T17:16:16.347 回答
1

- 反向可以很容易地使用Collections.reverse(List<?> l)

例如:

ArrayList<String> aList = new ArrayList<String>();

Collections.reverse(aList);

-使用For-Each循环打印出来。

例如:

for(String l : aList){

    System.out.print(l);

}
于 2012-10-22T17:28:08.807 回答
1
public static void main(String[] args) {


    int yil, bolum = 0, kalan;
    ArrayList liste = new ArrayList();
    System.out.println("Yıl Girin: "); // enter the 1453
    yil = 1453;

    String s="";
    do { // process makes 1453 separate then write in the arraylist like that [3, 5, 4,1]

        kalan = yil % 10;
        liste.add(kalan);
        s= s + kalan;  // <------- THE SOLUTION AT HERE  -------

        bolum = yil / 10;
        yil = bolum;

    } while (bolum != 0);

    System.out.println("Sayının Tersi: " + s ); //reverse of the 1453

}
于 2012-10-22T17:23:30.103 回答
0
List strings = ...
List stringsRevers = Collections.reverse(strings);
// Have to reverse the input
// 1,23 -> 231 
// otherwise it would be 321   
StringBuilder sb = new StringBuiler();
for(String s: stringsRevers ){
    sb.ppend(s);
}
String out = sb.toString();
于 2012-10-22T17:22:51.510 回答