tylerhunter1 tylerhunter1 - 2 months ago 7
Java Question

ArrayIndexOutOfBoundsException after String.split(\\s)

I am trying to split an input string into an array and then do something with each index of the array; however, the array only ever seems to be of size 1 no matter how many parts my string has.

Here's the code:

public void game() {

// print prompt and take input
System.out.print(">");
String string1 = in.next();

while (string1.length() != 0 ){

// splitting newArray into command and arguments
String[] newArray = new String[4];
newArray = string1.split("\\s+");

String command = newArray[0];
String newString = newArray[1];
String newString2 = newArray[2];
if (newString != null && newString2 != null){
int arg1 = Integer.parseInt(newString);
int arg2 = Integer.parseInt(newString2);
Cell c = cells[arg1][arg2];

if (command == "u") {
if (c.getMarked() == true) {
break; } // end if
else if (c.getMined() == true) {
uncoverAll();
System.out.println("You lose!");
break; } // end else if
else {
c.setUncovered();
if (allMinesMarked() == true && allNonMinesUncovered() == true) {
System.out.println("You win!");
break;
} // end if
} // end else
} // end if for "u"
else if (command == "m") {
if (c.getCovered() == false) {
break; } // end if
else if (c.getMarked() == true) {
c.setMarked(true); } // end else if
else {
c.setMarked(true);
if (allMinesMarked() == true && allNonMinesUncovered() == true) {
System.out.println("You win!");
break;
} // end if
} // end else
} // end else if for "m"
} // end if
else if (command == "show") {
show(); // prints the board
}
else if (command == "q") {
break; // exits while loop
}

else {
System.out.println("Bad command.");
}

System.out.print(">");
string1 = in.next();
} // end while
} // end game()


Stacktrace:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at MineSweeper.game(MineSweeper.java:215)
at MineSweeper.play(MineSweeper.java:271)
at Driver.main(Driver.java:4)


What I'm trying to accomplish is to split newArray[] into a 'command' (newArray[0]), and 'arguments' (newArray[1 and 2]). If there are no arguments, then it skips the first chunk of code, and if there are arguments, then it executes that code. But whatever I type on the command line I get the ArrayIndexOutOfBoundsException

Is there a way to set the specific index of the array to null if it doesn't come in through string1.split("\s+")? I've tried adding -1 to the split() entry but it hasn't done anything.

Answer

in.next(); only reads to the first whitespace character.

If you want to read multiple words, use in.nextLine(), and then this will work as expected.

String[] newArray = string1.split("\\s+");

Then, to solve your later problems, please read How to compare Strings in Java