javamethodscharvertical-text

String index out of range error - how do I print this string vertically in java?


I'm trying to print a statement vertically, and then backward vertically with two classes so I can practice multiple skills. However, frustratingly, I cannot get my program to work and keep getting a "string index out of range error". I'm not sure if I'm miscalling my functions because I am new to Java.

class Main {
  public static void main(String[] args) {

    MyString.verPrint("treasure");
    MyString.backPrint("treasure");

  }
}



public class MyString {
    
    public static String verPrint(String x){
      int i = x.length();
    while(0 < i){
      x = x.charAt(i) + "\n";
      i++;
    }
      return(x);
    }
      
    public static String backPrint(String x){
        int i = x.length() - 1;
      while(i >= 0){
          i--;
          x = x.charAt(i) + "\n";
        }
      return(x);
    }
}


Solution

  • The problem with your solution is you are updating the input string in the first iteration by assigning a character and a new line to it. Hence, it doesn't work for the latter iterations. I've made some changes in your snippet. You may follow it -

    public class Main {
      public static void main(String[] args) {
    
        System.out.println(MyString.verPrint("treasure"));
        System.out.println(MyString.backPrint("treasure"));
    
      }
    }
    
    class MyString {
    
      String x;
        
        public static String verPrint(String x){
          int i = x.length();
          String y = "";
          int j = 0;
          
        while(j < i){
          y += x.charAt(j) + "\n";
          j++;
        }
          return(y);
        }
          
        public static String backPrint(String x){
          int i = x.length() - 1;
          String y = "";
          
        while(i >= 0){
          y += x.charAt(i) + "\n";
          i--;
        }
          return(y);
        }
    }