1

When I am referencing lines as stringArray[i+2] (I mean, there was a problem with [i+1] as well), I get the ArrayIndexOutOfBoundsException. is there any way that I can safely reference those lines without the possibility of attempting to call an index that does not exist, without fundamentally changing my code?

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");
                }
                 }

         }

        }




        }
    }
camelCase
  • 49
  • 8

2 Answers2

0

The problem is that you are looping over the entire stringArray. When you get to the last elements of the stringArray and this

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

executes, stringArray[nextNew + 2] will not exist because you are at the end of the array.

Consider shortening your loop like so

for (int i = 0; i < stringArray.length - 3; i++) {
Burgan
  • 880
  • 1
  • 7
  • 24
  • Awesome! However, using for (int i = 0; i < stringArray.length - 3; i++) { was what got it working. – camelCase Feb 23 '18 at 03:22
  • Excellent, I've edited my answer to reflect this. Please consider accepting this answer if it worked for you. – Burgan Feb 23 '18 at 03:23
  • I did have one problem: I now need three meaningless strings added on to the end to counteract the reduction in strings that it is adding to the array. Is there anything that can be done to fix that? – camelCase Feb 23 '18 at 03:25
  • The amount of strings in the array is the same? – Burgan Feb 23 '18 at 03:33
  • Well, I am getting the strings from a .txt document, meaning it will not add the last 3 words of the document to the array. – camelCase Feb 23 '18 at 03:43
  • The array is populated by a different loop `//populating array with individual blocks for(int x = 0; x < blockCount; x++) {` – Burgan Feb 23 '18 at 03:46
0

Since you are already checking for last word, all you have to is move these 4 lines of code:

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

in your:

if (isLast == false) {

That should solve your problem. Also you should check for length - 1 and not length to check the last word.

for (int i = 0; i < stringArray.length; i++) {
        isLast = true;
         String currWord = stringArray[i].trim();

         if (stringArray.length-1 != i) {
             isLast = false;
         }
         String quotes = "\""; 

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

    // rest of the code
tryingToLearn
  • 10,691
  • 12
  • 80
  • 114