2014-09-07 1 views
0

이것은 내 첫 번째 게시물입니다. btw, 선생님은 수업에 프로그래밍에서 과제를 부여하고 우리는 회문 프로그램을해야합니다. 나는 그것을 할 수 있지만 오류를 없애고 싶다. 오류가있는 이유를 설명해 주시겠습니까? 어떻게 제거합니까?프로그램이 작동하고 있지만 오류가 있습니다. 문자열 색인이 범위를 벗어났습니다. -1

import java.io.*; 

public class AssignmentInCopro 

{public static void main (String [] args) throws IOException 
    {BufferedReader x = new BufferedReader(new InputStreamReader(System.in)); 

    String word = ""; 

    System.out.print("Please enter the word you want to see in reverse: "); 
    word = x.readLine(); 

    int wordLength = word.length(); 

    while (wordLength >=0) 
    { 
    char letter = word.charAt(wordLength - 1); 
    System.out.print(letter); 
    wordLength--; 
    } 
    } 
} 
+1

변경 반면에 조건'워드 길이> 0'합니다 (= 없음). –

답변

1

루프가 색인 0을 포함하는 동안 오류가 발생합니다. wordLength 경우 제로 그래서 당신이 charAt(-1)을 찾을 것입니다 당신은 예외를 얻을 :

가 코드를 변경

:

while (wordLength >0) 

그리고 오류가 사라지고있다.

0
while (wordLength >=0) 

워드 길이 = 0 다음 char letter = word.charAt(wordLength - 1); 실제로 letter = word.charAt(0 - 1);

while (wordLength >0) 

이 조건해야 숯불 또는이 같은 루프 쓸 수있는이 원인 오류 -

int wordLength = word.length() - 1; 
while (wordLength >=0){ 
    System.out.print(word.charAt(wordLength--)); 
} 
0

무슨 봐 wordlength가 실제로 0과 같을 때 // while (wordLength> = 0) -1 // word.charAt(wordLength - 1)에서 char에 액세스하려고합니다. 반면에

변화를 (워드 길이> 0) 또는 (워드 길이> = 1)

좋은 하루를

관련 문제