访问可能不存在的索引Java

时间:2018-02-23 03:10:40

标签: java

当我将行引用为stringArray [i + 2]时(我的意思是,[i + 1]也存在问题),我得到了ArrayIndexOutOfBoundsException。有没有什么方法可以安全地引用这些行而不会尝试调用不存在的索引,而不会从根本上改变我的代码?

import java.io.*;
import java.util.Scanner;

public class Test {

    public static void main(String [] args)  {



        /** Gets input from text file **/
        //defines file name for use
        String fileName = "temp.txt";

        //try-catches for file location
        Scanner fullIn = null;
        try {
            fullIn = new Scanner(new FileReader(fileName));
        } catch (FileNotFoundException e) {
            System.out.println("File Error : ");
        }
        Scanner in = null;
        try {
            in = new Scanner(new FileReader(fileName));
        } catch (FileNotFoundException e) {

            System.out.println("Error: File " + fileName + " has not been found. Try adjusting the file address or moving the file to the correct location." );
            e.printStackTrace();
        }



        //finds the amount of blocks in the file
        int blockCount = 0;
        for (;in.hasNext() == true;in.next()) {
            blockCount++;
            }




        //adding "" to every value of stringArray for each block in the file; created template for populating
        String[] stringArray = new String[blockCount];
        for (int x = 0; x == blockCount;x++) {
            stringArray[x] = "";
        }

        //we are done with first scanner
        in.close();



        //populating array with individual blocks
     for(int x = 0; x < blockCount; x++) {

         stringArray[x]=fullIn.next();

          }

     //we are done with second scanner
     fullIn.close();
     //for later
     Scanner reader;
    boolean isLast;
     for (int i = 0; i < stringArray.length; i++) {
        isLast = true;
         String currWord = stringArray[i].trim();
         int nextNew = i+1;
         String nextWord = stringArray[nextNew].trim();
         String thirdWord = stringArray[nextNew+1].trim();
         String fourthWord = stringArray[nextNew+2].trim();
         if (stringArray.length != i) {
             isLast = false;
         }
         String quotes = "\""; 

        if (isLast == false) {
        if (currWord.equalsIgnoreCase("say") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)) {
            System.out.println(nextWord.substring(1, nextWord.length()-1));
        }
        if (currWord.equalsIgnoreCase("say") && isFileThere.isFileThere(nextWord) == true){
            System.out.println(VariableAccess.accessIntVariable(nextWord));
        }
        if (currWord.equalsIgnoreCase("lnsay") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)){

            System.out.print(nextWord.substring(1, nextWord.length()-1) + " ");
        }
         if (currWord.equalsIgnoreCase("get")) {
             reader = new Scanner(System.in);  // Reading from System.ins
             Variable.createIntVariable(nextWord, reader.nextInt()); // Scans the next token of the input as an int
             //once finished
             reader.close(); 
        }

         if (currWord.equalsIgnoreCase("int") && thirdWord.equalsIgnoreCase("=")) {
            String tempName = nextWord;
            try {
                int tempVal = Integer.parseInt(fourthWord);
                Variable.createIntVariable(tempName, tempVal);
                } catch (NumberFormatException e) {
                System.out.println("Integer creation error");
                }
                 }

         }

        }




        }
    }

2 个答案:

答案 0 :(得分:0)

问题是你正在遍历整个stringArray。当你到达stringArray

的最后一个元素时
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();

执行,stringArray[nextNew + 2]将不存在,因为您位于数组的末尾。

考虑缩短你的循环

for (int i = 0; i < stringArray.length - 3; i++) {

答案 1 :(得分:0)

由于您已经在检查最后一个单词,所以您只需移动这4行代码:

#include <stdio.h>

int main()
{
    float value;
    value = 12345.1;

    printf("Value = %f\n", value);

    return 0;
}

在你的:

int nextNew = i+1;
 String nextWord = stringArray[nextNew].trim();
 String thirdWord = stringArray[nextNew+1].trim();
 String fourthWord = stringArray[nextNew+2].trim();

那应该可以解决你的问题。另外,您应该检查if (isLast == false) { 而不是length - 1来检查最后一个字。

length