-1

I am completely stumped in trying to read from a file and adding it to an array. So what I tried to implement was reading the line into a temporary String array, then adding the temporary value to the main array,

This is the contents of the text file I would like to split into an array line by line. So that i could take each line, do calculations with the numbers and format an output.

    Mildred Bush 45 65 45 67 65 into [[Mildred Bush],[45],[65],[67],[65]]
    Fred Snooks 23 43 54 23 76               etc.
    Morvern Callar 65 45 34 87 76            etc.
    Colin Powell 34 54 99 67 87
    Tony Blair 67 76 54 22 12
    Peter Gregor 99 99 99 99 99

However, when run whats in the main array is [Mildred, Fred, Morvern, Colin, Tony, Peter]. So meaning that only the first value is appended to the main array and im unsure of how to fix this in my code to what i require.

// The name of the file to open.

    String fileName = "Details.txt";

    String wfilename = "output.txt";

    // This will reference one line at a time
    String line = null;

    String temp;

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader(fileName);

        FileWriter fileWriter = new FileWriter(wfilename);


        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        List<String> parts = new ArrayList<>();
        String [] temp2;

        while((line = bufferedReader.readLine()) != null) {
            //System.out.println(line);
            temp = line;
            temp2 = line.split(" ");

            parts.add(temp2[0]);
            //System.out.println(line);
            bufferedWriter.write(line + "\n");
        }   
        System.out.print(parts);

        // Always close files.
        bufferedReader.close();   
        bufferedWriter.close();
    }
    catch(FileNotFoundException ex) {
        System.out.println("Unable to open file '" + fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println("Error reading file '" + fileName + "'");                  

    }

updated attempt:

I found that the reason for this was

    parts.add(temp2[0]);

yet when I tried

    parts.add(temp2)

i got hit with an error being

    The method add(String) in the type List<String> is not applicable for the arguments (String[])

So basically what i am struggling with is adding an array into an array.

edit2:

I tried

 for(int i=0; i<7; i++){
                parts.add(temp2[i]);
           }

which worked in that it added all the items in the file into one array. I was wondering if there was any method which can split the list every 7 terms to make it a 2D array?

This isnt required but i feel like for calculations it would be bad practice to use a for loop and do [i+7] when doing calculations for each line.

John
  • 13
  • 4
  • 1
    Have you tried to step through that code with a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems)? – litelite Nov 08 '17 at 16:00
  • Look at the [doc](https://docs.oracle.com/javase/7/docs/api/java/util/List.html) quite sure you will find something that allow you to add an array into an array in the first few methods ;) – litelite Nov 08 '17 at 16:04
  • 1
    there are problem in your split. it would split also the two words so [0] only return the first word. "Mildred Bush" will give you only "Mildred" which probably is not what you wanted – logger Nov 08 '17 at 16:05

2 Answers2

0

Try this:

           try{
                br = new BufferedReader(new FileReader("myfile.txt"));

                //Save line by line the file in ArrayList
                while( ( contentLine = br.readLine() ) != null ){               
                    arrlist.add(contentLine);
                }

                //Iterate the list and applies Split to get the data
                for(int i = 0; i < arrlist.size(); i++){
                    String[] splitString = arrlist.get(i).split(" ");
                        for(int j = 0; j < splitString.length; j++){
                            if(isNumeric(splitString[j])){
                                System.out.print(splitString[j]+"*");
                            }
                        }
                        System.out.println();
                }

            }catch(IOException io){
                io.printStackTrace();
            }

Here is the method isNumeric:

       public static boolean isNumeric(String str){  
          try{  
            double d = Double.parseDouble(str);  
          }  
          catch(NumberFormatException nfe){  
            return false;  
          }  
          return true;  
        }

I hope I've helped...

0

I had a similar problem and I found this solution for a multidimensional Array:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class Test {

    //first I read the file into a String
    static String readFile(String fileName) throws IOException {
        BufferedReader br;
            br = new BufferedReader(new FileReader(fileName));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                line = br.readLine();
                }
            return sb.toString();
        } finally {
            br.close();
        }
    }

    public static void main (String [] args) {
        String input = new String();
        try {
            input = readFile("Example.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Then I convert it
        String dimension1 = "\\|", dimension2 = " ", dimension3 = ","; //That could also be other characters

        String [] arrayString1D = input.split(dimension1);
        String [][] arrayString2D = new String[arrayString1D.length][];
        String [][][] arrayString3D = new String[arrayString2D.length][][];

        for(int x = 0; x < arrayString1D.length; x++) {
            arrayString2D[x] = arrayString1D[x].split(dimension2);
            arrayString3D[x] = new String [arrayString2D[x].length][];

            for(int y = 0; y < arrayString2D[x].length; y++) {
                arrayString3D[x][y] = arrayString2D[x][y].split(dimension3);
            }
        }

    //And here I print it out!
    System.out.println(Arrays.deepToString(arrayString3D));
    }
}

The Text in the txt. file could for example look like this:
word1,word2,word3,word4,word5|word6,word7 word8|word9,word10,word11 word12,word13

and it would print this :
[[[word1, word2, word3, word4, word5]], [[word6, word7], [word8]], [[word9, word10, word11], [word12, word13]]]

I hope that helps! :-)