2014-01-15 67 views
-3

我真的不知道如何編程...我在做這個的計算機科學類java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:7

Instruction: Use nested loops to print out the square word pattern show below. I'm guessing the error is in the toString method, but I can't spot where.

所需的輸出是: (當輸入爲正方形)

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); 

} 
} 
+0

請加上堆棧跟蹤012 –

+0

如果輸入是'平方',輸出應該是什麼? –

+0

使用IDE並調試程序。這並不難。 – Jayan

回答

1

請嘗試以下操作,我將解釋th在註釋ë修改:

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 
+0

我做了int i = 1,所以後來我做了word.length()-1-i – user3196544

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時出錯。

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))+ 「\ n」 個;此行正在使字符串索引超出界限例外

相關問題