파일을 읽은 다음 동일한 양의 닫는 대괄호와 열린 대괄호가 있는지 확인하는 프로그램을 작성하고 있습니다. 따라서 FileInputStream과 Scanner 클래스를 사용하여 파일을 읽고 각 문자를 ArrayList에 저장했습니다. 파일 읽기가 블록 주석으로 끝나지 않으면 대부분 내 프로그램이 작동합니다. 여기에 내 코드가있다. 예를 들어Java ArrayList IndexOutOfBound 파일에서 주석을 읽을 때
private Input input;
private ArrayList<Character> fileText;
public q1_19() {
input = new Input();
fileText = new ArrayList<Character>();
}
private void storeTextInArray(String name) {
FileInput readFile = new FileInput(name); //Makes use of Scanner and FileInputStream
while(readFile.hasNextChar()) {
fileText.add(readFile.nextChar());
}
readFile.close();
}
private boolean booleanChecker() {
int braces = 0;
boolean lineComment = false;
boolean blockComment = false;
boolean constant = false;
boolean string = false;
for (int i = 0; i < fileText.size(); i ++) {
//Case lineComment
if ((fileText.get(i) == '/') && (fileText.get(i+1) == '/') && ((i+1)<fileText.size())) {
lineComment = true;
}
if ((lineComment) && (fileText.get(i) == '\n')) {
lineComment = false;
}
//Case constant
if ((fileText.get(i) == '\'') && (fileText.get(i+2) == '\'') && ((i+2)<fileText.size())) {
constant = true;
i++;
}
//End String
if ((string) && (fileText.get(i) == '"')) {
string = false;
}
//End blockComment
if ((blockComment) && (fileText.get(i) == '*') && (fileText.get(i+1) == '/') && (i+1 < fileText.size())) {
blockComment = false;
if (fileText.lastIndexOf(fileText) == i) {
break;
}
}
if (!(lineComment || blockComment || constant || string)) {
//String constant
if (fileText.get(i) == '"') string = true;
if ((fileText.get(i) == '/') && (fileText.get(i+1) == '*') && (i+1 < fileText.size())) blockComment = true;
if (!(lineComment || blockComment || constant || string)) {
if (fileText.get(i) == '{') { braces ++; System.out.println("+1"); }
if (fileText.get(i) == '}') { braces --; System.out.println("-1"); }
}
}
constant = false;
}
System.out.println(braces);
if (braces != 0) return false;
else return true;
}
, 내가 {{}} /**/
을 읽으려고, 내가 얻을 오류가 나는 대부분의 파일을 읽을 수 있지만 난 그냥 이유를 이해하고 싶은대로 그것은 정말 문제가되지 않습니다 java.lang.IndexOutOfBoundsException: Index: 4, Size: 4 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429)
있습니다. StackFlow에 관한 나의 첫 질문이기 때문에 질문을 잘못하면 용서해주십시오. 고맙습니다.
당신의 길이가'0에서 반복하고 경우에 일어날 것입니다 - -
아래의 코드 라인의 난 = fileText.size()가 있다고 가정 해 봅시다 참조 1', 아직 당신은 'fileText.get (i + 1)'. 배열의 최대 배열 인덱스가'length - 1'이므로 배열의 범위를 벗어나고, 실제로 길이가 1에서'length'로 갈 것입니다. – Moira