java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:7

时间:2014-01-15 03:57:01

标签: java for-loop nested-loops

我真的不知道如何编程...我正在研究计算机科学课

  

说明:使用嵌套循环打印下面显示的方形图案。   我猜错误是在toString方法中,但我无法发现在哪里。

所需的输出是:(当输入为SQUARE时)

SQUARE
Q    R
U    A
A    U
R    Q
ERAUQS

代码:     import static java.lang.System。*;

class BoxWord
{
   private String word;

 public BoxWord()
 {
  word="";
 }

 public BoxWord(String s)
 {
   setWord(s);
 }

 public void setWord(String w)
 {
   word=w;
 }

 public String toString()
 {
  String output=word +"\n";
  for(int i =0;i<word.length(); i++){
    output += word.charAt(i);
    for(int j = 2; j<word.length();j++)
      output += " ";
    output+= word.charAt(word.length()-(i-1))+ "\n";
  }

  for(int k=0; k<word.length(); k++)
   output+= word.charAt(k);


  return output+"\n";
 }
}

主:

import static java.lang.System.*;

public class Lab11f
{
   public static void main( String args[] )
   {
     BoxWord test = new BoxWord("square");
     out.println(test);   

 }
}

3 个答案:

答案 0 :(得分:1)

尝试以下内容,我将在评论中解释修改:

public static void main(String[] args)
{
    String word = "square";
    String output = word + "\n"; // Initialize with the word
    for (int i = 1; i < word.length() - 1; i++) { // From '1' to 'length - 1' because we don't want to iterate over the first and last characters
        output += word.charAt(i);
        for (int j = 0; j < word.length() - 2; j++) // To add spaces
            output += " ";
        output += word.charAt(word.length() - (i + 1)) + "\n";
    }
    for (int k = word.length() - 1; k >= 0; k--) // Add word in reverse
        output += word.charAt(k);

    System.out.println(output);
}

<强>输出:

square
q    r
u    a
a    u
r    q
erauqs

答案 1 :(得分:0)

在此循环的前两次迭代中,您将出现错误:

for(int i =0;i<word.length(); i++){
    output += word.charAt(i);
    for(int j = 2; j<word.length();j++)
      output += " ";
    output+= word.charAt(word.length()-(i-1))+ "\n";
                         ^^^^^^^^^^^^^^^^^^^
  }

这相当于word.length() - i + 1,当i为0或1时,这将是一个错误。

答案 2 :(得分:0)

public String toString()
 {
  String output=word +"\n";
  for(int i =0;i<word.length(); i++){
    output += word.charAt(i);
    for(int j = 2; j<word.length();j++)
      output += " ";
    output+= word.charAt(word.length()-(i-1))+ "\n";
  }

输出+ = word.charAt(word.length() - (i-1))+&#34; \ n&#34 ;; 此行使字符串索引超出绑定异常< / p>