0

I try to print reverse of the entering number without any for loop. But I've got some issues with printing the Arraylist. How can I print the Arraylist [3, 5, 4, 1] as 3541 - without brackets, commas and spaces?

If not possible, how can I add my ArrayList elements to stringlist then print?

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

4 Answers 4

3
  • Read the entry as a String
  • Reverse it with String reverse = new StringBuilder(input).reverse().toString();
  • Optional: parse it to an int if you need to do some calculations with that int.
Sign up to request clarification or add additional context in comments.

3 Comments

[1,23] will become 321 insted of 231. I think tht ws the intented output.
My understanding is that the user enters one number (1453 in the given example) and the goal is to reverse that number (to 3541 in the given example). I might have misunderstood.
but, wht is, if one of the numbers lrger than 9? I think that is not clear.
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

}

1 Comment

StringBuilder would be better here for appending characters but this seems to be most appropriate to solve the overall FIFO problem here so +1!
1

- Reverse can be easily obtained using Collections.reverse(List<?> l)

Eg:

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

Collections.reverse(aList);

- Use For-Each loop to print it out.

Eg:

for(String l : aList){

    System.out.print(l);

}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.