2012-10-22 52 views
0

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

如果不行,我该如何将我的ArrayList元素添加到字符串列表然后打印?

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(); 
} 
+0

的http://stackoverflow.com/questions/196628/printing-out-items-in-any-collection-in-reverse-order – r0ast3d

+0

你为什么需要重复避免for循环? – jlordo

+0

你可以读取字符串而不是数字(或者你可以从int转换为String)并使用StringBuilder reverse()。 – nhahtdh

回答

2
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 

} 
+2

'StringBuilder'在这里可以更好地追加字符,但这似乎是最合适的解决FIFO的总体问题,所以+1! – Reimeus

4
  • 阅读条目作为字符串
  • String reverse = new StringBuilder(input).reverse().toString();
  • 可选扭转它:它解析为int,如果你需要做一些计算与INT。
+0

[1,23]将会成为321的321。我认为这是输出的结果。 –

+0

我的理解是用户输入一个数字(在给出的例子中为'1453'),目标是反转该数字(在给定的例子中为'3541')。我可能会误解。 – assylias

+0

但是,如果其中一个数字超过9?我认为这并不明确。 –

1
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(); 
2

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

如很容易地获得:

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

Collections.reverse(aList); 

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

如:

for(String l : aList){ 

    System.out.print(l); 

}