2009-12-18 49 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 2009-12-18 08:45:32

+1

Chente - 如果'another'是空字符串,則此錯誤只能**發生。更仔細地檢查你的斷言(理想情況下用一個調試器,以便你可以看到究竟發生了什麼)和/或實施Itay的建議,看看問題如何消失。 – 2009-12-18 08:58:54

回答

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 2009-12-18 08:52:01

+1

如果這個作品,你可以將其標記爲答案... – extraneon 2009-12-18 09:06:35

相關問題