• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Need a little help...

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let me preface this with the understanding that this is homework. However, I am looking for guidance, not complete answers and hope that you guys can help point me in the right direction. I am taking a basic JAVA course and abolutly love it. We are now working with files (input streams) and this is where I am having troubles (first time in this class). What I am trying to do is search a file for a specific species and then report the name, population and growth rate of that species. I have completed the code for the output file with no problems and it looks like this...

Name = Will
Population = 1
Growth Rate = 1.0%
Name = Eagles
Population = 22
Growth Rate = 33.0%

Simple enough....

However, when I read the file in I want to be able to search for "Eagles" and then return the three lines associated with it. I am using the BufferedReader but that is where I get lost. Our book states we can break the file down into individual words using StringTokenizer, but it give no example and I have had no luck googling it. So I come to you guys for aid.

Once again, I do NOT want answers as this does me no good. What I need is a link or hint showing me how this works...

Here is what I have so far and I am using Netbeans (maybe there is help that I haven't found in there...).


/* William Potere
*
* CMIS 141A
*
* FindSpecies.java
*
* Created on June 13, 2006, 11:04 AM
*/

package Project3;
import java.util.*;
import java.io.*;
/**
*
* @author william.potere
*/
public class FindSpecies {

public static void main(String [] args){
StringTokenizer tokenizer = null;
String name, line, newName;
char repeat;

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the file you wish to read:");
String fileName = keyboard.next();
// do{
try{

// Set up the input file stream
BufferedReader inFile = new BufferedReader(new FileReader(fileName));
System.out.println("Please enter the species that you are looking for:");
newName = keyboard.next();
line = inFile.readLine();
StringTokenizer st = new StringTokenizer(inFile.readLine());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
System.out.println(st.nextToken());
System.out.println(st.nextToken());
}


// System.out.println(line);
// line = inFile.readLine();
// System.out.println(line);
}
catch (FileNotFoundException e)
{
System.out.println("File " + fileName + " not found.");
}
catch (IOException e)
{
System.out.println("Error reading from file " + fileName);
}
}
}
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Forgot to mention, there are items in there that I have commented out. This is where I was playing. I also planning on putting a loop in so the user can run it again.
[ June 14, 2006: Message edited by: Will Potere ]
 
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch, Will.

Have you looked up StringTokenizer in the API recently? They have recently deprecated it, which means they prefer you to use the String.split() method.

What you have done is to read the line, divide it into "tokens," then print out each "token." You haven't yet done anything to check whether it is an "Eagle" or not. Remember you have your lines in threes, so you might be better reading 3 lines at a time, then analysing them later.

Does the book really suggest you put all your workings in the main method?

CR
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
CR,

Thanks for the reply. The book nor the instructor really care if I use one or more methods. She only cares that it works. The book is "JAVA an introduction to problem solving and programming" by Walter Savitch and really only covers the basics of reading a line. We were not informed that it was recently depreciated so that is why I am trying to use it.

I spoke with a friend of mine that stated I should try using inString but have not been able to find anything that would help.

OK, so, to fix this mess, let me start from here....

This line...

line = inFile.readLine();

makes the variable "line" only the FIRST line of the file and then, of course, I use the tokenizer to break it down as you said. Is there something other than readLine that will read the entire file? I think that is where I getting stuck. If I can find the line I am looking for and print it to screen, I can then tell the program to print the next two lines to fulfill the requirement. (keeping this simple for now). I know this may not be the best way to do it, but right now this is what I have. I'm going to look at your suggestion of String.split() and see what I can find.

You got my brain flowing again....
[ June 14, 2006: Message edited by: Will Potere ]
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK, still working it...

Here is what I can do...

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the file you wish to read:");
String fileName = keyboard.next();

try{


BufferedReader inFile = new BufferedReader(new FileReader(fileName));


line = inFile.readLine();
System.out.println(line);

This little bit will let me print the first line of the file to the screen. I have decided to hold off on the search portion until I can at least get the entire file printed to the screen and understand "how" it works.

Adding another

line = inFile.readLine();
System.out.println(line);

lets me print the first two lines of text.

Is there a method that I can use to print the entire file? (Oh, maybe a loop!)
[ June 14, 2006: Message edited by: Will Potere ]
 
Campbell Ritchie
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Is there something other than readLine that will read the entire file?

As far as I know, no. But you can use readLine three times, and have an array of lines. I presume you are familiar with the following formats for arrays?
Now you have a set of lines called 0 1 2 which you can manipulate separately.

Like everything else in computing, there are several ways to do it.

Do they insist you use StringTokenizer or String.split?

An alternative is to find the last index of the " " in the line read, and then use the "sub-string" consisting of the part of the line after it. Have you looked for similar methods in the String class?
Beware: any of these methods of splitting your Strings are very dependent on your spelling and formatting the text file exactly the same way every time.

Since Savitch (4/e) was printed in December 2004, he ought to cover the updates to J5. I am a bit surprised he tells you to use the BufferedReader class rather than the java.util.Scanner class for simple text file reading.

I had better get my own brain flowing now . . .
 
Campbell Ritchie
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your keyboard Scanner will allow you to write the file name (beware: what I said about spelling applies to file names too).

Did they tell you anything about closing whichever object you use for reading files?

Have you come across methods for finding out whether there is a next line in any of the classes? Have you come across methods for finding out whether a line has a particular number of letters in?
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
LOL, I am familer with the code you posted. I just tried the loop and it worked..

BufferedReader inFile = new BufferedReader(new FileReader(fileName));


line = inFile.readLine();
while (line != null){

System.out.println(line);
line = inFile.readLine();

This prints my enitre file to screen. So, step one down and it only took me two days to do it!

Duh!

Ok, now I need to add the ablity to search the file and only return. I know that I will have to change a lot of it, but I am starting to understand "how" it works.

I have the 4th Edition of his book and it states on page 656 that BufferedReader is the preferred class for reading from a file. I guess an update is needed. However, it may be a bit out of date, but it can never hurt to learn this method and Netbeans is not telling me that it is depreciated.
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, we did cover closing file streams. I just haven't added it yet. In the future that will be added BEFORE I run a program. Such a small file is not taxing on the system, but I can imagine what a large file could do.
 
Campbell Ritchie
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Get into the habit of putting all the bits you need into your code from the beginning. If you don't close the file reader, you can't get access to the same file again. You have to use this rather complicated method: the "finally" inside the "try" is the best way to make absolutely sure you close the file whatever happens

BufferedReader is a good way to read files, and is not deprecated, but Scanner is simpler, but may only be suitable for text files.

Beware of (line != null). If your text file ends with a return newline etc, then you will get a non-null line with no characters in. That will throw you when you try to analyse it. Try (line != null && line.length() > 0). And if you have a file reading method you will have to find a way to return your results.

CR
[ June 14, 2006: Message edited by: Campbell Ritchie ]
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are not going to believe this. I just logged in to check my class and she changed the requirements. All we have to do now is display the complete file on screen, not search. Because we haven't really covered it at this point, she didn't want to burden us with trying to figure it out. Well, I have that part complete, but now I WANT to get teh other part working.

FYI, your sample code is excellent. I plan on implementing that from now on as it does a great job. Thanks.

From here, I plan on taking a small break and complete what is needed for the lesson. Then I will work to finish the original request.
 
Campbell Ritchie
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, you have got 99% of it working, and all you have to do is put the bits together.
If you have the name you are looking for, eg "Eagle," have you found any String methods to allow you to see whether the String contains "Eagle?"

Pleased to help
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I take back what I said. I have part one and three done, but the search portion is still needed. So, I'll start a new program to do this. Back to the hair pulling. :roll:
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm back and I think I am much further along. First, my txt file was too complex (for me at this point... newbie). So, I fixed the output so that it looks like this.

Eagles 45 21.0
Horses 77 23.0

So no I have the name, population and growth rate on one line for each species.

There are several ways to searched as discussed above, but we are working with the String Tokenizer (the reason to fix the created file).

What I have now for my search code is this.



Where I am having a problem is right here...

if (name = serName)

netbeans tells me that I need a boolean statement. Once again I ask for a point in the right direction.

 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK, I found the basic error..

if (serName = name)

should be

if (serName == name)

Now I working flow issues.
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ugh, this is getting me.

Am I way off base?

 
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Originally posted by Will Potere:

OK, I found the basic error..

if (serName = name)

should be

if (serName == name)

Now I working flow issues.




Will,
There is a huge difference between (serName == name) and serName.equals(name) .
I would recommend you to find that from
http://java.sun.com/j2se/1.4.2/docs/api/
Campbell : By the way, only now I came to know that Stringtokenizer has been deprecated. Thanks for the information.
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ram,

That makes sense. Thank you for your tip. I am now able to get a little output to the screen, but my if, else statement is not working right yet. However, I am one step closer.

You guys are great! Looks like I found a new JAVA home.
 
Campbell Ritchie
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Glad to see you are making progress.

And by the way, there are two kinds of deprecated classes or methods. A few (eg Thread.stop()) are deprecated because they don't work.
Many (eg the Vector and StringTokenizer) classes are deprecated because something better has been developed. See the API, where you will find this sort of thing

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.

or even (in the Thread class description)

stop()
Deprecated. This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.



CR
 
Ramasubbhu Allur Kuppusamy
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Originally posted by Will :

That makes sense. Thank you for your tip. I am now able to get a little output to the screen, but my if, else statement is not working right yet. However, I am one step closer.


Will,
Try using equals() to compare contents of strings instead of == in the if()
construct. This should solve the problem.
 
Ramasubbhu Allur Kuppusamy
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Originally posted by Will :

That makes sense. Thank you for your tip. I am now able to get a little output to the screen, but my if, else statement is not working right yet. However, I am one step closer.



Will,
Try using equals() to compare contents of strings instead of == in the if()
construct wherever you are comparing Strings. This should solve the problem.
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You guys have been a great help. Thank you so much. In fact, I am getting closer. I can now search the file but I have one last bit to deal with. What I need to do is report back if the search name is not found. Here is what I have so far.

Any ideas of what I can do? Hints... Tips...
 
Campbell Ritchie
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This bit should be easy.
You haveWell, what do you put against and after an "if?"
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry for the multiple posts, but I am sort of using this thread to track my thoughts.

In the code, I use...



is there a String method for not equals? If there is, I can't find it. If so, I could write another if statement to execute it and dump out of the loop.
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Uhhh != perhaps?
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nope! How about if else?
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm grabbing at straws!

Ok, the book only talks about "if" and "else" so I am not sure what I can put with it to make the statement false.
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think that I have it. Sloppy and not the best, but it does work.

 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's more usual to use a boolean in that scenario

 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[I]Originally posted by Will Potere:



is there a String method for not equals?[/I]

Notice the '!'
[ June 16, 2006: Message edited by: Marilyn de Queiroz ]
 
Campbell Ritchie
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ok, the book only talks about "if" and "else" so I am not sure what I can put with it to make the statement false.



I was thinking about "if . . . else," but you don't have to put anything in the "else" to make the statement false. If the "if" is "true" then whatever remains must be "else," and vice versa. But then I thought that you would end up with one printout saying "found" and several saying "not found."

Joanne Neal is correct about use of a boolean, but I disagree with the bit aboutBTW: that quote needs to be inside your loop, before you ask people to enter "Y" to try again.

There is a much simpler way to do it. All you have to do is work out how to get the System to print out "Eagle not found" if you don't find it, using your boolean variable.

CR
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Joanne,

Thank you for your reply. I see what you are saying and that would be much better. There are so many ways to do something that I often forget about the basics like boolean.

This is what I ended with and it works, but I will try your stuff later.

 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All these suggestions are great as I am learing. Thank you all very much. Bottom line is that I got the program running and now I can tweak it. Either way I met the requirement for the class which takes a load off. Many thanks to you all for pointing me in the right direction without simply giving me the answers. I post a little later to let you know what the final coding looked like and see if I can get some better tips for performance.
 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Will,

I've read with interest your problem you have been working on. As I understand it, for each line read you want to print out whether the species was found or if the species is not found. From your last bit of code, look closely because there would appear to be a slight error with the reporting of not finding the species in the current line being checked.


You indicate in your loop that if the species is found , then print out the details of the species. But look at what you do next. You are reading the next line of the file, and then doing a check based on the next line in the file. By this definition, you will only be told that the species doesn't exist if the line you are checking within the file is the last line available.

Regards

Matt
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That was the whole point. Once he has found the species, he exits the loop by setting count equal to 1. He would only print the 'not found' message if he has reached the end of the file without finding a match.
[ June 16, 2006: Message edited by: Joanne Neal ]
 
Matt Gaunt
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rightio,

My misunderstanding. I thought he wanted to report it either being found or not for each line read in the file.

Regards

Matt
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Campbell Ritchie:
[CODE]
There is a much simpler way to do it. All you have to do is work out how to get the System to print out "Eagle not found" if you don't find it, using your boolean variable.

CR



I was leaving that as an exercise for the OP
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Joanne is indeed correct in her thinking. As it looks, it does work and I added a little extra to keep the bogus reporting of teh last record from happening. I have used the tools that I have learned and I know that it is ugly to say the very least. However, with all the small things that I have learned here, I can streamline it to work better and look better. Thanks to you all. I will be a regular around here as I continue my JAVA learning trek.
 
Will Potere
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, here is what I think will be what I submit. However, there are some other methods of sorting that I want to play with so I may come back for more help using the same project.

 
Campbell Ritchie
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have tried to compile your class; you will have problems because the number of statements and the number of tokens in your lines doesn't match.

Move the speciesFound value out of the try to the beginning of the method, so as to increase its scope. Then you can move the line which prints "not found" to just before the line which asks for a Y to repeat, and get rid of the bit about "line == null" as not really relevant to printing out "not found."

CR
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic