Brian Cheda
Brian Cheda

Reputation: 35

Converting numbers in a string array to a two dimensional int array

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.

Upvotes: 0

Views: 833

Answers (1)

kirecligol
kirecligol

Reputation: 876

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]);
}

Upvotes: 1

Related Questions