簡體   English   中英

StringIndexOutOFBoundsException:0

[英]StringIndexOutOFBoundsException: 0

我是Java的初學者,並且在用戶控制的do-while循環中遇到問題,該循環接受用戶輸入以重復執行。 這是循環末尾的代碼。

System.out.print("Do you wish to continue? (Y for yes " +
                            "/ N for no)");
        input = keyboard.nextLine();
        input.length();
        repeat = input.charAt(0);

        }while (repeat == 'Y' | repeat == 'y');

我知道它會因為值而拋出異常,但是由於要確保它相對簡單,所以無法弄清楚該如何解決。 謝謝您的幫助。

編輯1:Stacktrace:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 0 
at java.lang.String.charAt(Unknown Source) 
at FractionTest.main(FractionTest.java:59)

看起來您讀了空行,並返回了空字符串""因此那里沒有字符(甚至沒有第0個字符)。

通常會在nextLine其他nextABC方法(例如nextInt之后使用nextLine時發生,因為此類方法不占用行分隔符,並且nextLine會讀取文本,直到下一個行分隔符(或流的末尾)為止。

在這種情況下,您可以在nextInt之后添加nextLine以使用行分隔符。

無論如何要避免從空字符串和異常中讀取字符,您可以使用類似

} while (input.toLowerCase().startsWith("y"));

代替

    input.length();//this actually doesn't change anything, you can remove it
    repeat = input.charAt(0);

} while (repeat == 'Y' | repeat == 'y');

正如@Phesmo所提到的,您可能會得到長度為0的行。 這是一個晦澀的問題。 在調用nextLine()之前,您是否在Scanner上調用了nextInt()nextLong()nextShort()nextByte()nextBoolean() nextLine()


嘗試這個

System.out.print("Do you wish to continue? (Y for yes / N for no)");

char ans;
do {
   ans = keyboard.next().charAt(0);
   // filter input
} while (ans == 'Y' || ans == 'y' || ans == 'N' || ans == 'n');

repeat = ans;

} while (repeat == 'Y' | repeat == 'y');

文檔

String Scanner#next()
查找並返回此掃描儀的下一個完整令牌。 完整的標記在其前面,然后是與定界符模式匹配的輸入。

或這個

System.out.print("Do you wish to continue? (Y for yes / N for no)");    
repeat = keyboard.next("[YyNn]").charAt(0);

} while (repeat == 'Y' | repeat == 'y');

文檔

String Scanner#next(String pattern)
如果它匹配從指定字符串構造的模式,則返回下一個標記。

"[YyNn]"是字符類模式,表示匹配集合中的任何字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM