I am trying to split a string in the following format: AND 1 0
.
The logic method below takes in a String read using .nextLine()
.
While I am able to split the String into Array using the split method and \\s+
regex, I run into an ArrayOutOfBound error whenever I try to access the second value of the array.
The second and third index of the Array should contain the values '1' and '2' respectively - why does this yield an error?
Code:
import java.util.*;
public class HelloWorld {
public static int logic(String operator){
String[] splitted = operator.split("\\s+");
int val = 0;
System.out.println(splitted.length); //Returns 3
System.out.println(operator); //Returns AND 1 0
System.out.println(splitted[0]); //Returns AND
System.out.println(splitted[2]); //ERROR
return val;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int val = sc.nextInt(); //Error lies here, should be parsed as String.
if(val == 1){
int no_times = sc.nextInt();
for(int i = 0 ; i < no_times; i++){
System.out.println(logic(sc.nextLine()));
}
sc.close();
}
}
}
Input:
OR 1 1
AND 0 1
AND 1 0
OR 0 0
AND 0 0
OR 1 0
OR 0 1
OR 0 1
OR 1 1
OR 1 0