0

I am taking data in from a text file with the following information:

Jessica 80 90
Peter 106 50
Lucas 20 85
Sarah 90 40
John 35 12

This data is then being converted into a String array and being outputted by my code. I would like to be able to keep the Names in my string array while converting the numbers into an Array of int[][] so that I can manipulate the variables to find averages for students and the exam. My working code is as follows below:

import java.io.*;
import java.util.*;

public class Array_2D{

public static String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);

        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }

        bufferedReader.close();

        return lines.toArray(new String[lines.size()]);
}   

public static void inputstream() throws IOException {
       String filename = "data.txt";
       try {
           String[] lines = readLines(filename);
           for (String line : lines)
           {
               System.out.println(line);
           }
       } catch(IOException e) {
           System.out.println("Unable to create " + filename+ ": " + e.getMessage());
       }

Does anyone have any information that would help me convert the numbers from the string array to the int[][] so that I may manipulate the numbers by column and row? Thank you for your time.

1
  • 3
    You could use OOP and create a Student object for each line. That would result in a better more readable design. Commented Sep 26, 2017 at 18:25

1 Answer 1

1

In your code each line contains one name and two integer, this may not be generic but try something like that,

String names = new String[numberOfLines];
int scores[][] = new int[numberofLines][2];
for(int i = 0;i < numberOfLines;i ++){
  String words[] = lines[i].split("\\s+");
  names[i] = words[0];
  scores[i][0] = Integer.parseInt(words[1]);
  scores[i][1] = Integer.parseInt(words[2]);
}

Sign up to request clarification or add additional context in comments.

Comments

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.