Reputation: 43
How do I reverse my array output? Like "peter"
to "retep"
or "max"
to "xam"
I tried to use collections but it's not working
This is my code:
import java.util.Scanner;
import java.util.Collections;
public class sdf {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
}
for(int i = 0; i < my_friend_names.length; i++) {
System.out.println("Name: " + my_friend_names[i]);
}
Collections.reverse(input);
System.out.println("After Reverse order: " +input);
}
}
Upvotes: 2
Views: 831
Reputation: 1601
You are trying to print out input
which is of type Scanner. Try using StringBuilder
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
String reversedName = new StringBuilder(my_friend_names[i]).reverse().toString();
System.out.println("After reverse: " + reversedName);
}
Upvotes: 0
Reputation: 31
Seems you create a string array, but than proceed to try reverse the input. If you want to use collections you may do something like this:
List<String> list = Arrays.asList(my_friend_names);
Collections.reverse(list);
System.out.println("After Reverse order: " + list);
Upvotes: 3
Reputation: 986
I think it would be the best way to make a char[]
from the String
, reverse that char[]
and convert it back to a String
.
Something like this should do the job:
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
}
input.close();
for(String name : my_friend_names) {
System.out.println("Name: " + name);
}
for(int i=0; i<my_friend_names.length; i++) {
char[] characters=my_friend_names[i].toCharArray();
List<char[]> reverse=Arrays.asList(characters);
Collections.reverse(reverse);
my_friend_names[i]=new String(characters);
}
System.out.println("After Reverse order: ");
for(String name : my_friend_names) {
System.out.println("Name: " + name);
}
Let me know whether it works (or not)
Happy coding :) -Charlie
Upvotes: 0
Reputation: 36703
Your posted code does not compile, for example you call Collections.reverse() on your scanner variable.
Things that might help you.
Example, use StringBuilder.reverse() to update replace each item in the array with a reversed String
String[] my_friend_names = { "fred", "alice" };
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = new StringBuilder(my_friend_names[i])
.reverse().toString();
}
System.out.println(Arrays.toString(my_friend_names));
Output
[derf, ecila]
Upvotes: 1