2009-12-18 4 views
1

이상한 예외 코드가 나타납니다. 다음과 같이StringIndexOutOfBoundsException : 문자열 인덱스가 범위를 벗어났습니다. 0

내가 사용하려고 코드는 다음과 같습니다

do 
{ 
    //blah blah actions. 

    System.out.print("\nEnter another rental (y/n): "); 
    another = Keyboard.nextLine(); 
} 
while (Character.toUpperCase(another.charAt(0)) == 'Y'); 

오류 코드는 다음과 같습니다

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 
at java.lang.String.charAt(String.java:686) 
at Store.main(Store.java:57) 

선 (57)는 시작이다 "동안 ...".

제발 도와주세요.

+0

또 하나는 "Y"로 인스턴스화됩니다. "YES"로 인스턴스화 된 경우에도 동일한 오류가 발생했습니다. – Chente

+1

Chente -이 오류는 'another'가 빈 문자열 인 경우에만 ** 발생할 수 있습니다. 어설 션을보다 면밀하게 (디버거로 이상적으로 볼 수 있도록 이상적으로) 확인하거나 Itay의 제안을 구현하고 문제가 어떻게 사라지는 지 확인하십시오. –

답변

8

another이 빈 문자열 인 경우 문제가 발생합니다.

우리는 Keyboard 클래스가 무엇인지 알 수 없지만 아마도 nextLine 메서드는 빈 문자열을 반환 할 수 있습니다 ... 그래서 역시 확인해야합니다.

5

수정 :

do 
{ 
    //blah blah actions. 

    System.out.print("\nEnter another rental (y/n): "); 
    another = Keyboard.nextLine(); 
} 
while (another.length() == 0 || Character.toUpperCase(another.charAt(0)) == 'Y'); 

또는 더 나은 :

do 
{ 
    //blah blah actions. 

    System.out.print("\nEnter another rental (y/n): "); 
    while(true) { 
     another = Keyboard.nextLine(); 
     if(another.length() != 0) 
     break; 
    } 
} 
while (Character.toUpperCase(another.charAt(0)) == 'Y'); 

이 두 번째 버전이 실수로 Enter 키를 누릅니다 경우 "다른 임대 입력"인쇄되지 않습니다.

+0

정말 고마워요! 그것은 웅변적인 해결책입니다! – Chente

+1

그것이 작동하는 경우 답변을 표시 할 수 있습니다 ... – extraneon

관련 문제