2

I have these objects of arrays with information stored in them which i have extracted from a file. How can change these into an array, i think i am meant to use 2D arrays, i want to sort them and display the corresponding information from them.

while(kd.hasNext()){
        String data = kd.nextLine();
        String [] values = data.split(",");

        String wScore = "N/A" , lScore = "N/A", crowd = "N/A";

        String year = values[0];
        String premiers = values[1];
        String runnersUp = values[2];
        if (values.length > 6)
        {wScore= values[6];}
        if (values.length > 7)
        {lScore= values[7];}
        if (values.length > 8)
        {crowd= values[8];}

This is one line of the information in a very large file.

2005,Arsenal,ManU,Arsenal,WestHam,Y,2,3,40000

 So if the user enters: 
 2005 

I want the program to display:

 Year: 2005
 Premiers: Arsenal
 Runner Up: ManU
 Minor Premier: Arsenal

etc..

I try using a for loop for length of the array, but as i dont have the years and all the other objects in an array, i cant use that. I was wondering if anyone has a solution to that.

I am not allowed to use HashMap, ArrayList, collections and Open CSV according to my teacher.

3
  • 2
    Create a class with the properties you want to print , set the properties for each object and add it to an array of your class type.
    – AllTooSir
    Commented May 29, 2013 at 17:23
  • 1
    What so strict teacher! It is a very didactic exercise to learn arrays. Commented May 29, 2013 at 17:41
  • yeah...even our last assignment was like this, he is hell bound on failing everyone who has ever been interested in java.
    – roro
    Commented May 29, 2013 at 17:42

4 Answers 4

1

As stated in the comments, you will want to make a new class, called whatever you want, with as many fields as the text file might require. Make a couple different constructors for the different cases that might come up in terms of how much data is given for that year. from there its just a matter of making get/set methods for each field.

Basic framework:

public class YearlyInformation
{
    int years;
    string premier, runnersUp;

    public YearlyInformation(int year, string prem, string, runners)
    {
        years = year;
        premier = prem;
        runnersUp = runners;
    }

    int getYear(void)
    {
        return years;
    }

    void setYear(int year)
    {
        years = year;
    }

}

Obviously you would have to add more for each different field you could have, but that's the basic idea, and adding to that is as simple as copy and paste.

5
  • i understand the set/get methods but how would i use the data i have for the output? how would i link it back to the objects i have already created? thats the only think confusing me now.
    – roro
    Commented May 29, 2013 at 17:40
  • Just make an array of YearlyInformation of size n. run a for loop, presumably as long as your file has lines, calling a new constructor of YearlyInformation, and storing it in the appropriate index. After that, all the information you need is in that array of YearlyInformation. Get they year from the user, and then do another for loop (same length) and compare the users year to the return from getYear(). when they match, print out all the data
    – Nealon
    Commented May 29, 2013 at 17:45
  • You'll want to implement a ToString() method for that class as well to make the printing out easier.
    – Nealon
    Commented May 29, 2013 at 17:46
  • okaay thanks for that, i think i get it, i'll have a play around!
    – roro
    Commented May 29, 2013 at 17:46
  • good luck, feel free to update this with details/more questions
    – Nealon
    Commented May 29, 2013 at 17:47
0

A 2D array would definitely work, except that you would need to know how many rows you would have. I am assuming that the number of columns is consistent. If you don't have a way of knowing how many lines are in the file, a highly inefficient, but still valid way to do this would be to loop through the entire file once, counting the lines, the creating a 2d array with that many rows. Then each row holds that information. Then, to find the needed information, you'd just look through and check the first spot in each row.

0

If you want to store all lines in 2D array, you can use something like that:

public static void main(String[] args) throws Exception {

    FileInputStream inputStream = new FileInputStream("file.txt");
    InputStreamReader streamReader =new InputStreamReader(inputStream,"UTF-8");
    BufferedReader in = new BufferedReader(streamReader);

    int increment = 10;
    int size = 0; // number of lines
    String[][] all = new String[increment][];

    for(String line; (line = in.readLine()) != null;) {

        String[] data = line.split(",");

        all[size++] = data;

        if(all.length == size) {
            // Increment capacity
            String[][] tmp = new String[all.length + increment][];
            for(int i = 0; i < data.length; i++) {
                tmp[i] = all[i];
            }
            all = tmp;
        }

    }

    // Trim to size
    String[][] tmp = new String[size][];
    for(int i = 0; i < size; i++) {
        tmp[i] = all[i];
    }
    all = tmp;

Sorting: If your teacher not say nothing about java.util.Comparator:

    Arrays.sort(all, new Comparator<String[]>() {
        @Override
        public int compare(String[] a, String[] b) {
            // By year?
            int yearA = Integer.parseInt(a[0]);
            int yearB = Integer.parseInt(b[0]);
            return yearA - yearB;
        }
    });

Although it may not be very useful sort, because the structure does not allow a quick search.

Query: And finally the user input:

    String input = null;
    Scanner sc = new Scanner(System.in);
    do {
        System.out.print("Input the year: ");
        String year = sc.nextLine();
        for(int i = 0; i < size; i++) {
            if (all[i][0].equals(year)) {
                // out data
            }
        }

    } while (input == null || input.isEmpty());


}
1
  • thank you so much for your help, learnt a lot just reading that lol
    – roro
    Commented May 29, 2013 at 18:21
0
  1. Create a new class to hold the data (OneYearInfo in my example below). You can update the fields relevant to each particular line in your file.
  2. Create an array of that type of object, with length long enough to fit all years needed. For instance, if the first possible year is 1900 and the last possible year 2013, then use length 114. One you've done this you can add each object to the relevant place in your array - this way you can easily get it back when a user types in a year to display:

    final int FIRST_YEAR = 1900;
    final int LAST_YEAR = 2013;
    OneYearInfo[] years = new OneYearInfo[LAST_YEAR - FIRST_YEAR + 1];
    int year = //get the info from file
    OneYearInfo newYear = new OneYearInfo();
       //set all the relevant fields of newYear
    years[year - FIRST_YEAR] = newYear;//adds newYear to your array
    

Now when your user enters a year, you just need to get the relevant element in your array. So for instance the year 2005 should be the 106th element of your array i.e. element number 105:

OneYearInfo yearToReturn = years[userEntry - FIRST_YEAR];
//Now get all valid fields from yearToReturn and display them for your user

Your class OneYearInfo can either use an empty constructor with getters/setters for each field, or you can have a custom contructor for each possible combination of fields. If there are only a few possibilities, multiple constructors is preferable e.g.:

class OneYearInfo{
    private int year;
    private String premiers;
    //add all possible fields here

    //first constructor
    public OneYearInfo(int year, String premiers){
        this.year = year;
        this.premiers = premiers;
    }

    //second constructor
    public OneYearInfo(int year, String premiers, String minorPremiers){
        this.year = year;
        this.premiers = premiers;
        this.minorPremiers = minorPremiers;
    }

    //add more constructors

    //getters
    public int getYear(){
        return year;
    }
    //add more getters

    //you can add setters here if required

If constructors don't cover all possible cases, or if using constructors for all cases is not possible e.g. some combinations of cases are of same type such as (int year, String premiers) vs (int year, String minorPremiers). Both of these cases would be (int,String) so setters would be required instead.

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.