如何解决字符串索引超出范围错误-如何在Java中垂直打印此字符串?
我试图垂直打印一条语句,然后垂直向后打印两个类,以便可以练习多种技能。但是,令人沮丧的是,我无法使我的程序正常工作,并不断收到“字符串索引超出范围错误”。我不确定是否因为我不熟悉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);
}
}
解决方法
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);
}
你知道输出
,解决方案的问题是,您在第一次迭代中通过分配字符和换行来更新输入字符串。因此,它不适用于后面的迭代。我对您的代码段进行了一些更改。您可以按照它-
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);
}
}
,
您的条件有问题,同时检查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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。