Hi there, I am having a problem using this scanner. I would like to find a specific value in the text file
inside of my textfile is:

1     iamSamantha 143iluvu Samantha Jones 23 Female
2     AdamLambert ilove8 Adam Lambert 25 Male 
3      saharaDoneth doneth123 Doneth Sahara 28 Female 

heres my code:

String firstName=""; 
try{ 
fileRead=new FileReader(myFile);
scan=new Scanner(myFile); 
while(scan.hasNext()){
if(scan.next.equals(iamSamantha)){ 
firstName=scan.next();
} scan.nextLine();
} scan.close();
}catch(Exception e){ 
} 

I want to display the firstName using the username iamSamantha.

Thanks for the help..

Recommended Answers

All 4 Replies

Please do help me.
Thanks in advance

Thanks for the help.

Exactly what help do you need?

First, you need to look at how your problem formulate. The data inside your data file indicates that EACH LINE contains one record. If you look closely, it is similar to...

//username password firstname lastname age gender
/*
iamSamantha 143iluvu Samantha Jones 23 Female
AdamLambert ilove8 Adam Lambert 25 Male
saharaDoneth doneth123 Doneth Sahara 28 Female
*/

Next, you are using Scan class to read the data in. There are many ways to deal with this kind of data. One easy way is to read in EACH line as a long String first (using nextLine()). Then manipulate the string data. You could do the match/search or simply split the string before doing so. You should assume the data format is ALWAYS correct for now.

What you are doing is correct at the begining when you check for hasNext() before going into a loop. However, you are doing every thing wrong afterward.

Line 6, there is no scan.next but scan.next(). Then, the value inside equals() method must be a STRING. What you are using is a VARIABLE. You need to read on syntax of variable and string.

Line 7, even if you fix line 6, you will get password instead of first name in this line. Why? Because using next() is to move from the first chunk of string before a white space to the next. The next chunk of string is password, not first name.

Line 8, you discard the whole line data afterward. It is logically correct.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.