user3002761
user3002761

Reputation: 49

External files Java

So I'm having a bit of difficulty with this program I was assigned. Here is the prompt:

You are to read an external file of random integer values until the end of file is found. As you read the file you should determine how many numbers are less than the value 500 and how many numbers are greater than or equal to 500.

I have the data, and I know exactly how many numbers are supposed to be less than 500 and how many are greater than or equal to 500. The problem is that I don't know how to make the loop read until the end of the file is found, or how to print out the different lines to meet the conditions using if statements.

Here is my code:

import java.io.*;
import java.util.*;
public class Prog209a
{
    public static void main(String[] args) throws IOException
    {
    Scanner sf = new Scanner(new File( "C:\\Users\\Air\\Documents\\java \\Prog2220.in"));

    int maxIndx = -1;
    String text[] = new String[1000];

    while(sf.hasNext()==true)
    {
        maxIndx++;


    sf.close();
    }
 }

I'm not asking someone to write the code for me, but to help give me a place to start or some hint. I'm not really good at reading external files, but I'm trying to learn. Feedback is appreciated. Thanks!

Upvotes: 0

Views: 221

Answers (2)

slider
slider

Reputation: 12990

In extension to Makoto's answer, your strategy should be:

  1. Initialize three variables: currentNum, greaterThan, lessThan to zero.
  2. Start scanning file line by line. Parse each line and store the parsed value in currentNum.
  3. Test if currentNum is less than 500. If yes, then increment lessThan, otherwise decrement greaterThan.
  4. Keep doing this till you reach EOF.

Done.

Upvotes: 0

Makoto
Makoto

Reputation: 106389

Your Scanner instance will currently continue reading the file until it no longer has any lines to read. The only drawback is that you're not reading any lines.

Use Scanner#nextLine(), or any of its "cousins", to suit your needs in your program.

Upvotes: 1

Related Questions