我的程序基本上采用 ISBN 编号列表并确定它们是否有效。所以错误在: s1[l]=digits[i][l-1]+digits[i][l]; 这行代码使用 for 循环获取 ISBN 编号的部分总和。它下面的另一个循环取数组 s1 中所有整数的部分和。请帮忙?错误是:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
at ISBN.main(ISBN.java:67)
import java.util.*;
import java.io.*;
public class ISBN {
public static void main(String [] args) throws IOException{
//Reads file line by line
File ISBNFile = new File ( "isbn_input.txt" );
Scanner input = new Scanner(ISBNFile);
String [] preISBN = new String [9999];
int i = 0;
int j =0;
int l =0;
int m = 0;
int count =0;
while (input.hasNextLine()){
String line = input.nextLine();
preISBN [i] = line;
i++;
count++;
}
input.close();
//Makes new array with specified count
String [] ISBN = new String [count];
String [] ISBNresult = new String [count];
for(i=0;i<ISBN.length;i++){
ISBN [i] = preISBN [i];
}
// int [] s1 = new int =
int [] [] digits = new int [ISBN.length] [12];
int [] s1 = new int [12];
int [] s2 = new int [12];
//Loads digits [] [] with values that will later be summed
for(i=0;i<ISBN.length;i++){
if(ISBN[i].length()!=12){
ISBNresult [i] = "Invalid";
continue;
}
for(j=0;j<12;j++){
if(ISBN[i].charAt(j)=='X'||ISBN[i].charAt(j)=='x'){
digits [i] [j] = 10;
}
else if(ISBN[i].charAt(j)=='-'){
digits [i] [j] = 0;
}
else
if(ISBN[i].charAt(j)==1||ISBN[i].charAt(j)==2||ISBN[i].charAt(j)==3||ISBN[i].charAt(j)==4||ISBN[i].charAt(j)==5||ISBN[i].charAt(j)==6||ISBN[i].charAt(j)==7||ISBN[i].charAt(j)==8||ISBN[i].charAt(j)==9){
digits [i][j] = Character.getNumericValue(ISBN[i].charAt(j));
}
else{
ISBNresult[i] = "Invalid";
break;
}
}
}
for(i=0;i<ISBN.length;i++){
for(j=0;j<ISBN[i].length();j++){
if(ISBN[i].length()!=12){
ISBNresult [i] = "Invalid";
continue;
}
s1[0]=digits[i][0];
for(l=1;l<=12;l++){
s1[l]=digits[i][l-1]+digits[i][l];
}
s2[0]=s1[0];
for(m=1;m<=12;m++){
s2[m]=s2[m-1]+s1[m];
}
}
if(s2[12]%11==0){
ISBNresult[i]="Valid";
}
else{
ISBNresult[i]="Invalid";
}
}
File outFile = new File("isbn_output.txt");
FileWriter fWriter = new FileWriter (outFile, true);
PrintWriter pWriter = new PrintWriter (fWriter);
for(i = 0;i<ISBN.length;i++){
pWriter.println (ISBN[i]+ " "+ ISBNresult[i] );
}
pWriter.close();
}
}