- Create a new class named StringTraversal.
- Add the following code to a main method.
public class StringTraversal { public static void main(String[] args){ String fruit = args[0]; for(int i = 0; i < fruit.length(); i++){ char letter = fruit.charAt(i); System.out.print(letter); } System.out.println(); } }
- Compile and run the program.
$ javac StringTraversal.java JAMESs-MacBook-Pro:~ jamesbrannan$ java StringTraversal banana banana
- Add the following lines to the end of main.
String r = ""; for(int i = fruit.length()-1; i >= 0; i--){ r = r + fruit.charAt(i); } System.out.println(r);
- Compile and run the program.
$ javac StringTraversal.java $ java StringTraversal banana banana ananab
The completed class should appear as follows.
public class StringTraversal { public static void main(String[] args){ String fruit = args[0]; for(int i = 0; i < fruit.length(); i++){ char letter = fruit.charAt(i); System.out.print(letter); } System.out.println(); String r = ""; for(int i = fruit.length()-1; i >= 0; i--){ r = r + fruit.charAt(i); } System.out.println(r); } }