Reputation: 21
So I am reading in a line from a file, that looks like:
Snowman:286:355:10
And this is the first part of the code I wrote to separate the data and place it into arrays.
for (int i = 0 ; i<manyItems; i++)
{
a = 0;
temp = scan.nextLine();
System.out.println(temp);
b = temp.indexOf(':');
System.out.println(b);
items[i] = temp.substring(a,b);
System.out.println(items[i]);
System.out.println(temp);
a = b;
System.out.println(temp);
b = temp.indexOf(a+1,':');
System.out.println(b);
rawX[i] = temp.substring(a+1,b);
System.out.println(rawX[i]);
}
It separates "Snowman" places it into the array, however, when I try to find the second colon, indexOf() keeps returning -1. Does anyone know why it is not finding the second colon?
Upvotes: 1
Views: 2241
Reputation: 629
There's a method under String
class that will handle the job for you. Split(regEx pattern)
is what you may want to use. The following code will do the job you're trying to perform:
String input = "Snowman:286:355:10";
String tokens [] = input.split(":");
for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);
Upvotes: 0
Reputation: 3165
Because you swapped the arguments of the indexOf call. It expects the character, then the index to start looking at. Remember that chars are ints, you're looking for the char 7 starting at the int value of ':'.
Upvotes: 4
Reputation: 28753
I think you have the arguments backwards:
b = temp.indexOf(a+1,':');
Should be...
b = temp.indexOf(':', a+1);
From docs.oracle.com:
public int indexOf(int ch, int fromIndex)
The first argument is the ch
aracter, the second if the fromIndex
.
Upvotes: 4
Reputation: 262494
You could save all that code and use String#split to split the line:
String[] parts = temp.split(":");
Upvotes: 7