I have a small homework application that writes random numbers from 5 to 77 to a text file and then I have a different application that reads this and add it to a totalAmount that has been initialized to 0.
I want to display the totalAmount as the number is added to the totalAmount with each loop.
with this I add the numbers to the text file
And with this I read the numbers
The output however starts with
and it end with
I am expecting that it should start with a random number such 40 for example and the adding it to the totalAmount with a new random number being added to the totalAmount with the next loop.
Why do I get this. Just trying to understand the logic
Nothing is jumping out at me that would cause that problem.
I would advise you to add a bunch of println statements (or use a debugger) so that you can see what's happening each step of the way. What numbers are getting generated? What's in the file? (Use Notepad or something to look at it.) What string is being read in each time? What is the int you're getting from it?
And set your array size to something more manageable--like 10--until you get a handle on this.
A couple other general pieces of advice that have nothing to do with your problem in particular (or at least probably don't).
1) This is bad:
Catching an exception doesn't actually fix anything, and just swallowing an exception like that says "I don't want to know if something went wrong. I just want to keep going as if everything is fine, even though it's not". At the very least, call io.printStackTrace(); so you can see what went wrong.
2) After writing to the file, you need to call close() on the "outermost" Stream or Writer. In this case it would be pw.close();. In the real world, that's called in a finally block, but you don't necessarily have to worry about that just yet.
3) The randomNumbers array is pointless. You're not actually using it. You can get rid of it and just have a single int randomNumber variable. (Unless you've got other code that you haven't shown that is using it.)