Search code examples
javaarraysstringdelimiter

Reading file data into two arrays (not array lists)


I have a file:

A,0.3
B,0.1
C,0.2
 ...

And I want the resulting arrays to be of the form:

String[] symbols = {A, B, C, ...}

Double[] frequencies = {0.3, 0.1, 0.2, ...}

I have figured this out using ArrayList (.add() is nice), but after some design decisions, I want the data in regular arrays. Obviously my implementation below does not work, but it's the closest I've come:

while (scan.hasNextLine()) {
        count ++;             // Number of lines incremented

        String[] parts;
        parts = r.split(",");

        // Store symbols into its own array
        for(int i = 0; i < count; i ++)
                syms[i] = parts[0];

        // Store frequencies into its own array
        for(int i = 0; i < count; i ++)
                freqs[i] = Double.parseDouble(parts[1]);
        }

Count keeps track of the amount of scanned lines (true while conditions), which at first seemed unnecessary to me, but I'm trying it now. Hence the help. Thanks.


Solution

  • Solved: i have created an array of 5 but the good procedure is to use array-list to increase decrease the size of array dynamically

     public static void main(String[] args) throws IOException {
    
    String[] myArray;
    double[] doubleArray = new double[5];
    String[] strArray= new String[5];
    
         int inc1=0;
         int inc2=0;
         FileReader fileReader = new FileReader("test.txt");
         Scanner s= new Scanner(fileReader);
    
         while(s.hasNext()){
               myArray= s.next().split(",");
           // to store double values
        for (String getStr: myArray) {
            if(isDouble(getStr)==true){
                doubleArray[inc1]= Double.parseDouble(getStr);
                inc1++;
            }
           // to store string values
            else {
                strArray[inc2]=getStr;
                inc2++;
            }
      }
      }
    
          for(String ss : strArray){
                 System.out.println("str value-> : "+ ss);
             }
             for(Double nnn : doubleArray){
                 System.out.println("double value-> : " + nnn);
             }
    
          fileReader.close();
    
    }
    

    check its convertible or not if its than it sends true else false

     public static boolean isDouble( String input ) {
        try {
            Double.parseDouble(input );
            return true;
        }
        catch( Exception e ) {
            return false;
        }
    }
    

    Testfile contains:

    A,0.3 
    B,0.1 
    C,0.2
    d,0.4 
    e,0.5 
    

    output :

    str value-> : A
    str value-> : B
    str value-> : C
    str value-> : d
    str value-> : e
    double value-> : 0.3
    double value-> : 0.1
    double value-> : 0.2
    double value-> : 0.4
    double value-> : 0.5
    

    hope answered the question if its useful than vote up