Practicing your craft is very important part of being a developer. Let`s try a simple exercise using Strings. For this exercise write a program that takes input from a user, the input should be a string, and then write a method that is using a String as a parameter and that returns a new string as a return value. The new string should contain the same letters as the parameter, but in reverse order.
Try it out. If you are stuck, scroll down for a solution.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Scanner; public class ReverseString { public static void main (String [] args) { Scanner s = new Scanner(System.in); System.out.println("Please enter a word: "); String word = s.nextLine(); System.out.println(reverse(word)); } public static String reverse (String reverseWord) { String word = ""; for(int i = reverseWord.length()-1; i>=0; i--) { word=word+reverseWord.charAt(i); } return word; } } |
You have a better solution, fell free to share it with everyone.
Happy coding!