[英]Why am I getting this error, eventhough I am getting result?
在下面的代碼中獲取異常:
import java.io.*;
public static void main(String[] args) throws IOException{
FileReader objRead = new FileReader("/home/acer/Desktop/sulabh");
BufferedReader objB = new BufferedReader(objRead);
String input = null;
while((input=objB.readLine())!= null){
String temp = input.substring(0,2);
if(temp.contains("77")) {
System.out.println(input);
}
}
objB.close();
}
答案錯誤是:
777
777
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 2, length 0 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319) at java.base/java.lang.String.substring(String.java:1874) at Main.main(Main.java:10)
您是否要從csv文件中讀取內容?
來自子字符串的java文檔:
Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
你的String temp = input.substring(0,2);
在得到兩條好的線后,得到一條比長度 2 短的線。
防止這種情況如下。
String temp = "";
if (input.length()>=2){
temp = input.substring(0,2);
}
我想前兩行已經處理得很好,最后會為空行拋出錯誤。 請檢查文件末尾是否有空行。 空白行可能包含少於 2 個字符。
或者,您也可以嘗試input.startsWith("77")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.