[英]Java method CharAt crashes at comparing to #
因此,我想做的是查看文本文件中字符串是否以#開頭。 但是,當我用#
調用charAt(0)
的比較時,會出現錯誤。
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at StringTranslator.main(StringTranslator.java:63)
代碼本身看起來像這樣(做所有比較的部分)
String line;
line = br.readLine())
if(line.charAt(0) == '#')
{
// this is a comment line ignore it
writer.println(line);
}
有什么建議如何得出結果並使其識別#
符號嗎? 先感謝您! 注意:在記事本中寫入文件和在代碼中讀取文件時,我都使用UTF-8 encoding
!
崩潰與#
無關。 您正在嘗試評估空字符串中的第一個字符。 訪問字符串之前,您應該驗證字符串是否為空:
if (line.length() > 0 && line.charAt(0) == '#')
錯誤“字符串索引超出范圍:0”表示您的字符串不包含任何字符,即為空字符串。
您需要檢查字符串是否不為空或不為null,然后檢查索引0處的字符是什么
if (!StringUtils.isEmpty(line) && line.startsWith("#")) {
// do something
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.