Reputation: 1
I am working on a problem: take a sequence of any characters as an argument to a method and then the method needs to take them and print out the same sequence forwards and backwards.
My problem is I am confused by the characters. I understand how to do this with int, or String, but I don't understand how to do it with chars. My thoughts were could I use a buffer, or maybe a collection list? I'm just looking for some pointers to lead me in the right direction. Thank you.
Upvotes: 0
Views: 68
Reputation: 9041
"a sequence of any characters" seems very vague to me.
"Hello"
resembles a sequence of characters as a String
"Hello".toCharArray()
resembles a sequence of characters as a char[]
123456
resembles a sequence of characters as an int
Having said that, an approach to this could go in many different directions. This approach addresses the 3 examples I've listed using overloaded methods.
public static void main(String[] args) throws Exception {
reverse("Hello");
reverse("Racecar".toCharArray()); // Palindrome
reverse(123456);
}
// Add more overloads for other data types
public static void reverse(int ints) {
reverse(String.valueOf(ints));
}
public static void reverse(char[] chars) {
reverse(new String(chars));
}
public static void reverse(CharSequence chars) {
System.out.println(chars);
System.out.println(new StringBuffer(chars).reverse());
}
Results:
Hello
olleH
Racecar
racecaR
123456
654321
Upvotes: 1