I need this program to accept user input in the following format: "team1 : team2 : score1 : score2" then assign it to the array variables below, which is working fine but now I need to make it so when the user enters 'stop' the program displays the results and stats of the data in the array. The problem is that when you enter stop it tries to add it to the array but as I have split the input into 4 parts, it just gives me an error (exception)
"java.lang.ArrayIndexOutOfBoundsException" error on the "awayteam = results[1];" line.
My question is: how can I make it so if the user enters 'stop' it doesn't try to add it to the array.
// Sample input: Chelsea : Arsenal : 2 : 1
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
int sum = 0;
System.out.println("please enter match results:");
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between the
// dash
// character
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
//convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
//stop command
if (s.equals(SENTINEL)) {
System.out.println("stopped");
}
// print results
}
}
}
Move the part "Stopped" with a break
to break out of the loop.
if (s.equals(SENTINAL)) {
System.out.println("Stopped");
break;
}
before split(" : ")
And also you don't need a dummy for loop.
You may do this instead :
while ( sc.hasNextLine() )
{
String s = sc.nextLine();
if (s.equals(SENTINAL)) {
break;
}
.....
}
sc.close();
Also remember to close the scanner - sc.close();