2014-01-15 3 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

친절하게 스택 추적을 추가합니다. –

+0

입력이'square'이면 출력은 무엇입니까? –

+0

IDE를 사용하고 프로그램을 디버깅하십시오. 그리 어렵지 않습니다. – Jayan

답변

1

다음을 시도해보십시오. 주석 E 수정 :

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을" ;이 줄은 문자열 인덱스를 경계 밖 예외로 만듭니다.

관련 문제