Print Page Print Page

CH9 – String Traversal

  1. Create a new class named StringTraversal.
  2. 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();
  }
}
  1. Compile and run the program.
$ javac StringTraversal.java 
JAMESs-MacBook-Pro:~ jamesbrannan$ java StringTraversal banana
banana
  1. 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);
  1. 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);
  }
}