![](/img/trans.png)
[英]I am getting “ java.lang.StringIndexOutOfBoundsException: String index out of range: -3 ”
[英]I am unable to solve this :java.lang.StringIndexOutOfBoundsException: String index out of range: 54
我想將存儲在兩個文本文件中的整數值相加(求和),並將其總和顯示為輸出,但是在運行代碼后,它給出了一個異常:java.io.FileNotFoundException:
public static void main(String[] args) throws IOException{
String path="C:/Users/MYPC/Desktop/text.txt";
String path2="C:/Users/MYPC/Desktop/temp.txt";
FileReader fr=null;
FileReader fr2=null;
try{
fr=new FileReader(path);
fr2=new FileReader(path2);
int i,sum=0;
int i2;
Scanner sc=new Scanner(path);
sc=new Scanner(path2);
while((i=fr.read())!=-1 &&((i2=fr2.read())!=-1 )) {
int read1=sc.nextInt(i);
int read2=sc.nextInt(i2);
sum = sum + read1+read2;
}
System.out.println(sum);
System.out.println(sum);
} catch(Exception ex) {
System.out.println(ex);
} finally{
fr.close();
}
}
通過將數字傳遞給nextInt
方法,您可以指定基數。 因此,例如,如果在給定的迭代中,您的i
值為2
,則表示您需要二進制。 如果不選擇基數,它將以10為基數掃描。
就是說, FileReader
read()
讀取下一個字符,因此您不需要掃描器即可在任何地方掃描下一個整數。
如下所示更改try塊內的代碼(未測試):
fr = new FileReader(path);
fr2 = new FileReader(path2);
while ((i = fr.read()) != -1 && (i2 = fr2.read()) != -1) {
char c = (char) i;
char c2 = (char) i2;
if (Character.isDigit(c) && Character.isDigit(c2)) {
int n = Character. getNumericValue(c);
int n2 = Character.getNumericValue(c2);
sum += (n + n2);
} else {
// TODO handle this somehow
}
}
為什么在下面編寫:fr2 = new FileReader(“”);
然后使用fr2讀取(i2 = fr2.read())!=-1)
因此,在哪里讀取fr2,其路徑為空字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.