Home > Blockchain >  Indexing through an array to return any specific value in java
Indexing through an array to return any specific value in java

Time:07-16

So, I have created code which is reading a CSV file line by line, then splitting each line into their individual values then putting this into an array, but i am stuck on trying the index a value from this array I have created, I will attach the CSV file and also my code, and lets say for example how would I access the value at [3,4], which should be Andorra, and [6,6] which should be 17?

CSV FILE:

Date,iso3,Continent,CountryName,lat,lon,CumulativePositive,CumulativeDeceased,CumulativeRecovered,CurrentlyPositive,Hospitalized,IntensiveCare,NUTS
31/1/2021,AFG,AS,Afghanistan,33.930445,67.678945,55023,2400,,52623,,,AF
31/1/2021,ALB,EU,Albania,41.156986,20.181222,78127,1380,47424,29323,324,19,AL
31/1/2021,DZA,AF,Algeria,28.026875,1.65284,107122,2888,,104234,,,DZ
31/1/2021,AND,EU,Andorra,42.542268,1.596865,9937,101,,9836,44,,AD
31/1/2021,AGO,AF,Angola,-11.209451,17.880669,19782,464,,19318,,,AO
31/1/2021,AIA,NA,Anguilla,18.225119,-63.07213,17,0,,17,,,AI
31/1/2021,ATG,NA,Antigua and Barbuda,17.363183,-61.789423,218,7,,211,,,AG
31/1/2021,ARG,SA,Argentina,-38.421295,-63.587403,1915362,47775,,1867587,,,AR
31/1/2021,ARM,AS,Armenia,40.066181,45.111108,167026,3080,,163946,,,AM
31/1/2021,ABW,NA,Aruba,12.517713,-69.965112,6858,58,,6800,,,AW
31/1/2021,AUS,OC,Australia,-26.853388,133.275154,28806,909,,27897,,,AU
31/1/2021,AUT,EU,Austria,47.697542,13.349319,411921,7850,383158,21058,1387,297,AT
31/1/2021,AZE,AS,Azerbaijan,40.147396,47.572098,229935,3119,,226816,,,AZ
31/1/2021,BHS,NA,Bahamas,24.885993,-76.709892,8174,176,,7998,,,BS
31/1/2021,BHR,AS,Bahrain,26.039722,50.559306,102626,372,,102254,,,BH
31/1/2021,BGD,AS,Bangladesh,23.68764,90.351002,535139,8127,,527012,,,BD
31/1/2021,BRB,NA,Barbados,13.18355,-59.534649,1498,12,,1486,,,BB
31/1/2021,BLR,EU,Belarus,53.711111,27.973847,248336,1718,,246618,,,BY
31/1/2021,BEL,EU,Belgium,50.499527,4.475402,711417,21118,,690299,1788,315,BE
31/1/2021,BLZ,NA,Belize,17.192929,-88.5009,11877,301,,11576,,,BZ
31/1/2021,BEN,AF,Benin,9.322048,2.313138,3786,48,,3738,,,BJ
31/1/2021,BMU,NA,Bermuda,32.320236,-64.774022,691,12,,679,,,BM
31/1/2021,BTN,AS,Bhutan,27.515709,90.442455,859,1,,858,,,BT
31/1/2021,BWA,AF,Botswana,-22.344029,24.680158,21293,134,,21159,,,BW
31/1/2021,BRA,SA,Brazil,-14.242915,-53.189267,9118513,222666,,8895847,,,BR
31/1/2021,VGB,NA,British Virgin Islands,18.573601,-64.492065,141,1,,140,,,VG

CODE:

public static String readFile(String file) {
    FileInputStream fileStream = null;
    InputStreamReader isr;
    BufferedReader bufRdr;
    int lineNum;
    String line = null;
    try {
        fileStream = new FileInputStream(file);
        isr = new InputStreamReader(fileStream);
        bufRdr = new BufferedReader(isr);
        lineNum = 0;
        line = bufRdr.readLine();
        while ((line != null) && lineNum < 27) {
            lineNum  ;
            System.out.println(line);
            line = bufRdr.readLine();
        }
        fileStream.close();
    }
    catch (IOException e) {
        if (fileStream != null) {
            try {
                fileStream.close();
            }
            catch (IOException ex2) {
            }
        }
        System.out.println("Error: "   e.getMessage());
    }
    return line;
}

private static void processLine(String line) {
    String[] splitLine;
    splitLine = line.split(",");
    int lineLength = splitLine.length;

    for (int i = 0; i < lineLength; i  ) {
        System.out.print(splitLine[i]   " ");
    }
    System.out.println("");
}

CodePudding user response:

You need to create a 2D array in readFile. As the file is read, and and each line is split by processLine, insert the array into the 2D array. The method readFile at the end returns the 2D array. Make processLine to return a string array and have it return the result of the split.

I marked where I made changes to your code.

import java.io.*;

public class Main
{
   public static void main(String[] args){
      String[][] data = readFile("data.txt");
      System.out.println(data[3][4]);
      System.out.println(data[6][6]);
   }
   
   public static String[][] readFile(String file) {  //<<< changed 
    FileInputStream fileStream = null;
    InputStreamReader isr;
    BufferedReader bufRdr;
    int lineNum;
    String line = null;
    String[][] data = new String[28][];  //<<< added
    try {
        fileStream = new FileInputStream(file);
        isr = new InputStreamReader(fileStream);
        bufRdr = new BufferedReader(isr);
        lineNum = 0;
        line = bufRdr.readLine();
        while (lineNum < 27) {  // <<< changed
            System.out.println(line);
            line = bufRdr.readLine();
            if (line == null) break;  // <<< added
            data[lineNum  ] = processLine(line);  // <<< added
        }
        fileStream.close();
    }
    catch (IOException e) {
        if (fileStream != null) {
            try {
                fileStream.close();
            }
            catch (IOException ex2) {
            }
        }
        System.out.println("Error: "   e.getMessage());
    }
    return data;  //added
}

private static String[] processLine(String line) {  //<< changed
    String[] splitLine;
    splitLine = line.split(",");
    int lineLength = splitLine.length;

    for (int i = 0; i < lineLength; i  ) {
        System.out.print(splitLine[i]   " ");
    }
    System.out.println("");
    return splitLine;  // <<< added
}

}

CodePudding user response:

You can do it quite simply using the stream API.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CsvTest0 {

    public static void main(String[] args) {
        Path path = Paths.get("geografy.csv");
        try (Stream<String> lines = Files.lines(path)) {
            String[][] arr = lines.skip(1L)
                                  .limit(27L)
                                  .map(l -> l.split(","))
                                  .collect(Collectors.toList())
                                  .toArray(new String[][]{});
            System.out.println(arr[3][3]);
            System.out.println(arr[5][6]);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

However, regarding the code in your question, below is a fixed version followed by notes and explanations.

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CsvTest1 {
    public static String[][] readFile(String file) throws IOException {
        Path path = Paths.get(file);
        String[][] arr = new String[27][];
        int lineNum;
        String line = null;
        try (BufferedReader bufRdr = Files.newBufferedReader(path)) {
            lineNum = 0;
            line = bufRdr.readLine(); // Ignore first line of file since it contains headings only.
            line = bufRdr.readLine();
            while ((line != null) && lineNum < 27) {
                arr[lineNum  ] = processLine(line);
                line = bufRdr.readLine();
            }
        }
        return arr;
    }

    private static String[] processLine(String line) {
        return line.split(",");
    }

    public static void main(String[] args) {
        try {
            String[][] arr = readFile("geografy.csv");
            System.out.println(arr[3][3]);
            System.out.println(arr[5][6]);
        }
        catch (IOException x) {
            x.printStackTrace();
        }
    }
}

Note that the below is not in any particular order. I wrote them as they came to me.

  • No need for FileInputStream and InputStreamReader in order to create BufferedReader. Use Files class instead.
  • Close files in a finally block and not in a catch block. Hence use try-with-resources.
  • I believe better to propagate the exception to the calling method, i.e. method main in this case. I also believe that, unless you can safely ignore the exception, it is always beneficial to print the stack trace.
  • You don't want to process the first line of the file.
  • You appear to have your array indexes mixed up. According to sample data, Andorra is row 3 and column 3 (not column 4). Also, 17 is at [5][6] and not [6][6].
  • Two-dimensional arrays in java can be declared with only one dimension indicated. Since you only want first 27 lines of file, you know how many rows will be in the 2D array.
  •  Tags:  
  • java
  • Related