0

我正在尝试垂直打印一个语句,然后用两个类垂直向后打印,这样我就可以练习多种技能。然而,令人沮丧的是,我无法让我的程序运行并不断收到“字符串索引超出范围错误”。我不确定我是否因为我是 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);
    }
}

4

3 回答 3

0
String s="HELLO";
        char[] y=s.toCharArray();
        for (char x : y) {
            System.out.println(x);
        }

输出
H
E
L
L
O

String S="Hello";
        S=new StringBuffer(S).reverse().toString();
        System.out.println(S);
char[] y=S.toCharArray();
            for (char x : y) {
                System.out.println(x);
            }

你知道输出

于 2020-11-11T06:14:15.303 回答
0

您的条件有问题,同时检查 x 字符串参数的长度和索引:

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

        System.out.println(verPrint("treasure"));
        System.out.println("-----------");
        System.out.println(backPrint("treasure"));
    }

    public static String verPrint(String x) {
        int i = 0;
        String result = "";
        while (i < x.length()) {
            result += x.charAt(i++) + "\n";
        }
        return result;
    }
    
    public static String backPrint(String x) {
        int i = x.length() - 1;
        String result = "";
        while (i >= 0) {
            result += x.charAt(i--) + "\n";
        }
        return result;
    }
}
于 2020-11-11T07:23:39.863 回答
0

您的解决方案的问题是您在第一次迭代中通过为其分配一个字符和一个新行来更新输入字符串。因此,它不适用于后面的迭代。我在您的代码段中做了一些更改。你可以关注它——

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);
    }
}
于 2020-11-11T06:19:30.183 回答