2

I'm writing up a program that goes into a basic .txt file and prints certain things. It is a comma-deliminated file. The file includes 7 first and last names, and also 4 numbers after. Each of the seven on a separate line. Each line looks like this: George Washington, 7, 15, 20, 14. The program has to grab the last name and then average the 4 numbers, but also average the first from all seven, second from all seven, etc. I'm not sure on how to start approaching this and get it to keep grabbing and printing what's necessary. Thanks for any help. I appreciate it.

0

6 Answers 6

2

Hint:

Tutorial:

Extract of relevance from the tutorial:

To use a different token separator, invoke useDelimiter(), specifying a regular expression. For example, suppose you wanted the token separator to be a comma, optionally followed by white space. You would invoke,

s.useDelimiter(",\\s*");
Sign up to request clarification or add additional context in comments.

Comments

1

A scatch:

public static void main(String[] args) throws IOException {
    int[][] numbers = new int[7][4];
    String[] names = new String[7];
    BufferedReader reader = new BufferedReader(new FileReader("datafile"));
    String line;
    int row = 0;
    while ((line = reader.readLine()) != null) {
        String[] cells = line.split(",");
        names[row] = cells[0].trim();
        for (int i = 1; i < cells.length; i++) {
            numbers[row][i - 1] = Integer.parseInt(cells[i].trim());
        }
        row++;
    }
    for (int i = 0; i < names.length; i++) {
        System.out.printf("%s, %.2f%n", names[i], avg(numbers[i]));
    }
    // Do the other average calculation
}
private static double avg(int[] numbers) {
    int sum = 0;
    for (int i = 0; i < numbers.length; i++) {
        sum += numbers[i];
    }
    return sum / numbers.length;
}

2 Comments

I'm using a Mac to do all of this programming and it needs to run on Windows so I'm using : File Grades = new File(System.getProperty("user.home"), "grades.txt"); so how would I use that to read from the file?
FileReader accepts a File object as argument as well, so you can use your Grades File object, like this new FileReader(Grades)
0

Hint:

  • BufferedReader.readLine()
  • StringTokenizer

4 Comments

I'm using a Mac to do all of this programming and it needs to run on Windows so I'm using : File Grades = new File(System.getProperty("user.home"), "grades.txt"); so how would I use that to read from the file?
new BufferedReader(new FileReader(grades)) will give you a BufferedReader that will let you read a line at a time from the file.
I'm doing this and I got it to work. But when I get to while ((line = Grades.readLine()) != null I'm getting an error that says the readLine() is a symbol that cannot be found.
Don't use the FileReader, since it depends on the Default Platform Encoding.
0
File file = new File("C:\\data.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try {
  fis = new FileInputStream(file);

  // Here BufferedInputStream is added for fast reading.
  bis = new BufferedInputStream(fis);
  dis = new DataInputStream(bis);

  // dis.available() returns 0 if the file does not have more lines.
  while (dis.available() != 0) {

    /* Read the content from file */
    /* Read a line and check if first element before first comma is a string */
    /* Read four numbers separated by comma after first comma in an arraylist */
    /* Loop around array list to get the average of numbers */
    /* Store the first number from this record in another vector */

    System.out.println(dis.readLine());
  }

  // dispose all the resources after using them.
  fis.close();
  bis.close();
  dis.close();

} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

Comments

0

I'd personally recommend looking at the split method for strings (so you could break up a line into an array of strings) Or stringTokenizer as Brian suggested.

The rest is just calculations and having an array to store it in.

1 Comment

Don't use the FileReader, since it depends on the Default Platform Encoding.
0

There are some things to consider:

The files on your disk are stored as a sequence of bytes, but when processing text, you need sequences of characters. Therefore, when loading the file, you need to convert the bytes to characters. This can be simply done using these three types:

FileInputStream fis = new FileInputStream("data.txt");
Reader rd = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader brd = new BufferedReader(rd);

The buffered reader provides a method readLine that is handy for reading input line by line.

Then you would process one line of input at a time. You split the line at all points that consist of some whitespace, a comma, and some whitespace. The regular expression for that is "\\s*,\\s*".

Now you have an array of fields. The first field is the name, which you can use as is. The other fields need to be converted to integer numbers, which can be done with Integer.valueOf(String).

When you have read all lines, you should close the file.

4 Comments

I'm using a Mac to do all of this programming and it needs to run on Windows so I'm using : File Grades = new File(System.getProperty("user.home"), "grades.txt"); so how would I use that to read from the file?
File gradesFile = new File(System.getProperty("user.home"), "grades.txt"); (note that the variable name starts with a lower-case letter) and then FileInputStream fis = new FileInputStream(gradesFile);.
Ok. That's all good except it's not compiling because it says cannot find symbol for Charset.
Hopefully your integrated development environment has a feature called organize imports, which will do all the work for you. Otherwise you have to google.de/search?q=java+charset, click on the first link and discover that the Charset class lives in java.nio.charset, so you have to import java.nio.charset.Charset;.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.