-2

I am trying to reverse array String from the user and I had one problem how can I out put the elements without new array. I don't know what should I write to output the content. However, I tried most of the examples*(a[i], a[i+1]) and if run it I got null.

here is my code:

import java.util.Scanner;
public class ReverseArray {
    public static void main(String[] args) {
    int i=0;
    String temp =null;
    String o=null;
    int pos =0;
    String a [];
    Scanner kb = new Scanner (System.in);
    System.out.print("Enter a sentence: "); 
    o = kb.nextLine(); 
    a = new String [o.length()];

    for( i =0; i< (o.length()/2)-1; i++){
        temp = a[i];
         a[i] = a[o.length()-(i+1)];
         a[o.length()-(i+1)] = temp;
    }
}
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • Use [Arrays.toString](http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) to output the contents of an array, combined with `System.out.println`, of course. – DavidS Oct 27 '16 at 23:01
  • System.out.println(new StringBuilder("reverse this string").reverse().toString()); – Kylar Oct 27 '16 at 23:04
  • 2
    A lesson in [MCVE](http://stackoverflow.com/help/mcve) - We don't care how you get a string, so cut out all of the input blurb and just give us `String o = "string to reverse";` – John3136 Oct 27 '16 at 23:05
  • I ll try so thank you – Tariq Almaashni Oct 27 '16 at 23:45

2 Answers2

0

Collections.reverse(asList(arraytoReverse));

wrap your array within asList() then call the collections' reverse on the list created.

HaroldSer
  • 2,025
  • 2
  • 12
  • 23
0

It's printing null because you are not providing the string to the array of the string. So, it printing null. If you want to reverse the array of string you can simply use a delimiter to read the string into the array of string. And to reverse it you can use StringBuilder and string.append() method to concatenate the string. If you just want to reverse a string just use StringBuilder and reverse() method. Try the following code :

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a sentence: ");
    String str = in.nextLine();
    StringBuilder sb = new StringBuilder(str).reverse();
    System.out.println(sb.toString());

}

Output :

 Enter a sentence: This is a string
 gnirts a si sihT
thetraveller
  • 445
  • 3
  • 10