LarryDCJ
LarryDCJ

Reputation: 3

In an array with two objects, how can I be getting an out of bounds exception at (1)?

I'm getting an "ArrayIndexOutOfBoundsException: 1" error, but only when "q" is entered to exit the program.

import java.util.Scanner;

public class ParseStrings {
   public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in);
  Scanner  inSS = null;
  String userInfo = "";
  String firstWord = "";
  String secondWord = "";
  String[] names = {"",""};


  System.out.println("Enter input string: ");
  userInfo = scnr.nextLine();

  boolean isFound = userInfo.contains(",");

  if (isFound == false) {
        System.out.println("Error: No comma in string");
        System.out.println("Enter input string: ");

        userInfo = scnr.nextLine();
        isFound = userInfo.contains(",");
     }

     while (isFound) {

        names = userInfo.split(",");

        firstWord = names[0];
        secondWord = names[1]; //<----- LINE 33

        System.out.println("First word: " + firstWord.trim());
        System.out.println("Second word: " + secondWord.trim());
        System.out.println("");
        System.out.println("");

        System.out.println("Enter input string: ");
        userInfo = scnr.nextLine();

     }

      if (userInfo == "q") {
           System.exit(0);
      }
   return;
   }
}

The intent of the program is to separate strings/lines consisting of two words, separated by a ",". This part works perfectly, but the program fails when "q" is entered to exit.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at ParseStrings.main(ParseStrings.java:33)

Upvotes: 0

Views: 87

Answers (2)

Kamdem Nathan
Kamdem Nathan

Reputation: 1

You should add this: isFound = userInfo.contains(","); at the end of the while code block.

The issue seems to be the fact that the while loop will never stop.

Upvotes: 0

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31215

Here :

names = userInfo.split(",");

When userInfo contains only q, names will be {"q"}, an array of only one element.

Hence, names[1], which is the second element of names does not exist.

Hence the ArrayIndexOutOfBoundsException.

You might refactor it like this :

while (isFound) {
  if (userInfo.equals("q")) { // btw, notice the 'equals' instead of ==
    System.exit(0);
  }
  names = userInfo.split(",");
  firstWord = names[0];
  secondWord = names[1]; 
  [...]

Upvotes: 2

Related Questions