0

In this program I am trying to return the user input backwards e.g. Laura would be returned as aruaL, but I am getting [C@11d72ca as my output..

    String input = JOptionPane.showInputDialog("Enter name");
    Scanner scanner = new Scanner(input);
    String name = scanner.next();
    scanner.close();

    char[] backwards = new char[name.length()];
    for(int i = 0; i<name.length(); i++)
    {
        backwards[i] = name.charAt(name.length()-1-i);
    }

    JOptionPane.showMessageDialog(null, backwards.toString());
}
l-l
  • 3,804
  • 6
  • 36
  • 42
  • Your code *will* print the string correctly, it's just that you're not printing the array correctly. – Makoto Apr 16 '15 at 01:47

1 Answers1

0

There is an easier way to reverse a string:

    String reverse = new StringBuilder(name).reverse().toString()

If you don't want to use this method, in order to covert a char[] to a string you would need to do something like:

    String reverse = new String(backwards);

Calling toString on an array will call the toString method of the Object. This will return you the hashCode which is what you are getting

l-l
  • 3,804
  • 6
  • 36
  • 42