Reputation: 622
I am trying to extract information from a file that is formatted as follows:
1
[email protected]|password|false
However, I seem to be getting ArrayIndexOutOfBounds
errors when running the following code and I am unable to determine the reason for this as I believe that my splitting should be functioning correctly. The error is obtained on the line beginning with "users".
sc = new Scanner (System.in);
BufferedReader in = new BufferedReader (new FileReader (USAVE));
int repeats = Integer.parseInt(in.readLine());
for (int c = 0; c < repeats; c++){
String info = in.readLine();
System.out.println (info);
String[] extracted = info.split("\\|");
users.addUser(extracted[0], decryptPassword(extracted[1]));
}
in.close();
What could be the problem?
EDIT: I have changed "|" to "\|" but the problem persists.
EDIT2: StackTrace
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at OnlineCommunications.userFromFile(OnlineCommunications.java:165)
at OnlineCommunications.logIn(OnlineCommunications.java:36)
at OnlineCommunications.emailOption(OnlineCommunications.java:593)
at OnlineCommunications.main(OnlineCommunications.java:683)
The method I have posted above is the one named userFromFile
.
Upvotes: 1
Views: 169
Reputation: 36
Actually there is nothing wrong with how you are parsing the string. The error lies elsewhere. I would add System.out.println (repeats) just before you enter the loop to make sure you are iterating the correct number of times. To debug even further, I would print the contents of extracted (Arrays.toString(extracted)) before the line invoking user.addUsers. If all that looks good, then the problem lies in the user.addUsers invocation.
Upvotes: 0
Reputation: 10139
similar post. Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*' You have to use like this :
String[] extracted = info.split("\\|");
Upvotes: 1
Reputation: 117579
String.split(String regex)
takes a regular expression as an argument, use:
String[] extracted = info.split("\\|");
Upvotes: 2
Reputation: 46398
String#split(regex) expects regex as a parameter and |
is a meta character(special character) in regex world. In order to treat a meta charcter as a normal character you should escape it with backslash(\|)
String[] extracted = info.split("\\|");
or just include it inside a charcter class
String[] extracted = info.split("[|]");
Below are the meta characters in regex:
<([{\^-=$!|]})?*+.>
Upvotes: 6