【问题标题】:java.lang.StringIndexOutOfBoundsException: String index out of range: 7java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:7
【发布时间】:2014-01-15 03:57:00
【问题描述】:

我真的不知道如何编程......我正在为计算机科学课做这个

说明:使用嵌套循环打印出如下所示的方字图案。 我猜错误出在 toString 方法中,但我找不到位置。

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

SQUARE
Q    R
U    A
A    U
R    Q
ERAUQS

代码: 导入静态 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);   

 }
}

【问题讨论】:

  • 请添加堆栈跟踪
  • 如果输入是square,那么输出应该是什么?
  • 使用 IDE 并调试程序。这并不难。
  • 看看当 i = 0 时会发生什么。

标签: java for-loop nested-loops


【解决方案1】:

试试下面,我会解释在cmets中的修改:

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

【讨论】:

  • 我做了 int i = 1 所以后来我做了 word.length() -1-i
【解决方案2】:

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

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 时会出错。

【讨论】:

    【解决方案3】:
    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";
      }
    

    output+= word.charAt(word.length()-(i-1))+ "\n"; 这一行使字符串索引越界异常

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 2016-02-25
      • 2018-11-14
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      相关资源
      最近更新 更多