Hello, I'm new in Java and I have a problem with Tokenizer.
I'm writing a program which the user enters his username and password and the program checks if that username and password exits. The user database is in a text file called "userlist.txt". The file looks like this:
Where in the first pane column is the username and in the second the password (obviously! ). I know how to separate the columns (relatively easy), here's the code:
That piece of code produces this:
Now here's the problem. I want the user to type his/her username and the program will check if that username exists (in this case, the possible usernames are user1, user2 or user3). And if the username exists the program will ask the password and checks if that's correct. And I have no idea how to check certain words in a tokenized file. I know it has something to do with nextToken() but I can't figure it out. What worries me the most is that the program will not search the whole file, but instead, it will search in which line the username exists and then will check the password.
Any ideas or something to point me to the right direction? I'm stuck.
Thank you in advance.
"Somewhere, something incredible is waiting to be known." - Carl Sagan
"Ah, I love your religion - for the crazy! Virgin birth, water into wine; it's like Harry Potter, but it causes genocide and bad folk music." - Roger (Seth McFarlane)
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
You're lying. Put bluntly, but it's true. That code does not produce an array with elements "2" and "Pizza". It produces an array with elements "", "2", "|", "|", "P", "i", "z", "z", "a", "|", "|", "|" and "|", and the reason can be found in my previous post - you split at "nothing", so each element becomes its own array element, including the leading empty string. Your output can be created using a StringTokenizer(splittable, "||||").
But that's not using String.split, which you said you were using.
OK, the reason for your problem. StringTokenizer is garbage. Eh, I mean, StringTokenizer uses characters for splitting. Not sequences of characters. There is no difference in behaviour between new StringTokenizer(splittable, "||||") and new StringTokenizer(splittable, "|"). In both cases it still uses only | to split. Multiple occurrences of | will be regarded as one separator.
Using String.split (for real this time) you can solve this, but remember to not use splittable.split("||||"), for reasons I already mentioned. You must escape those pipe symbols.