0

I have a set of data that look like this.

1:2:3:4:5
6:7:8:9:10

I have manage to use array list to store the information using a delimiter of ":". However i would like to store the information of their line numbers together in the array list.

class test
{
   String items;
   String linenumber;

}

 Example:
    test(1,1)
    test(2,1)
    test(6,2)
    test(7,2)

Here is my current code.

 Scanner fileScanner = new Scanner(new File(fname));
     fileScanner.useDelimiter("\n");
     int counter = 0; String scounter;
     String test;
     String events;

     while(fileScanner.hasNext())
     {


               events = fileScanner.next();
               scounter = Integer.toString(counter); 

       Base obj = new Base(scounter, events);
           baseArrayList.add(obj);


     }

    fileScanner.close();

I have try using delimiter "\n" and then trying to split out the string and it is not very successful. Any advice would be appreciated.

    public void Base_Seperator()
     {
    String temp, temp2;
    String[] split;
    String days, events;
    for(int i = 0; i < baseArrayList.size(); i++)
    {
       temp = baseArrayList.get(i).events;
       temp2 = baseArrayList.get(i).days;

       split = temp.split(":");


    }

  }
  • Is the number of items in each line constant? Ie. will there always be 5 elements? – rath May 24 '14 at 19:15
  • There will not always be fixed 5 elements. The number of items vary i believe. However it is assume that each line will be a day. And that every item is an event. –  May 24 '14 at 19:17
  • how do you want the arraylist to look? do you want the elements of the line to be followed by the line number or are you looking for a multi-dimensional array where each line is its own sub-array? – Bryan May 24 '14 at 19:23
  • Actually i have posted in my question test(1,1) so with events and then line number. I have a class object arraylist for storing it the problem was how to add in the line number associated with the event. –  May 24 '14 at 19:25

3 Answers3

2

Despite the code in @Alex's answer that may solve your problem, your attempt is almost close to get what you want/need. Now you only need to create Test instances and store them in a container, usually a List. I'll add the necessary code to start this from your code:

//it is better to return the List instead of declaring it as a static field
public List<Test> Base_Seperator() {
    //try to declare variables in the narrower scope
    //String temp, temp2;
    //String[] split;
    //String days, events;

    //this variable must be recognized in all the paths of this method
    List<Test> testList = new ArrayList<Test>();
    for(int i = 0; i < baseArrayList.size(); i++) {
        //these variables should only work within the for statement
        String temp = baseArrayList.get(i).events;
        String temp2 = baseArrayList.get(i).days;
        String[] split = temp.split(":");
        //you have splitted the String by :
        //now you have every element between : as an item stored in split array
        //go through each one and create a new Test instance
        //first, let's create the lineNumber variable as String
        String lineNumber = Integer.toString(i+1);
        //using enhanced for to go through these elements
        for (String value : split) {
            //now, let's create Test instance
            Test test = new Test(value, lineNumber);
            //store the instance in testList
            testList.add(test);
        }
    }
    //now just return the list with the desired values
    return testList;
}

Not part of your question, but some advices:

  • There are plenty other ways to write code to achieve the same solution (take @Alex's answer as an example). I didn't posted any of them because looks like you're in learning phase, so it will be better for you to first achieve what you're looking for with your own effort (and a little of help).

  • Not sure if you're doing it (or not) but you should not use raw types. This is, you should always provide a generic type when the class/interface needs it. For example, it is better to define a variable as ArrayList<MyClass> myClassList rather than ArrayList myClass so the class become parameterized and the compiler can help you to avoid problems at runtime.

  • It is better to always program oriented to interfaces/abstract classes. This means, it is better to declare the variables as an interface or abstract class rather than the specific class implementation. This is the case for ArrayList and List:

    List<String> stringList = new ArrayList<String>();
    //above is better than
    ArrayList<String> stringList2 = new ArrayList<String>();
    

    In case you need to use a different implementation of the interface/abstract class, you will have to change the object initialization only (hopefully).

More info:


Looks like you want to store days instead of lineNumber in your Test instances:

//comment this line
//Test test = new Test(value, lineNumber);
//use this one instead
Test test = new Test(value, days);
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Thanks for your advice. Yes i have much to learn. I will keep it in mind. –  May 24 '14 at 19:36
  • I have tried the code however it seems that it would append the line number increasingly. The reason i have thought that temp2 could store and retrieve that and match it with the items that are store with events. So with temp 1:2:3:4:5 and temp2 1 the new arraylist would store ArrayList(1,1) ArrayList(2,1) –  May 24 '14 at 20:13
  • @LennonChia check my edit. If that's not what you're looking for, then adapt the code to your exact needs. – Luiggi Mendoza May 24 '14 at 20:20
  • Thank you i will take a look once i get some sleep. –  May 24 '14 at 20:25
  • thanks for your advice. I have manage to get it after some modification. –  May 25 '14 at 07:35
1

First of all you don't need to keep line number info in the test object because it can be inferred from the ArrayList that holds them. If you must though, it should be changed to an int. So,

class test
{
    ArrayList items<Integer>;
    int linenumber;

    public test(int line, String[] input){
        items=new ArrayList();

        linenumber=line;

        //populate with the line read by the Scanner
        for(int i=0; i<input.lenth; i++)
             items.add(Integer.parseInt(input[i]));
    }
}

I use an ArrayList inside test because you don't know how many elements you'll be handling. Moving on to the scanner

 Scanner fileScanner = new Scanner(new File(fname));
 // fileScanner.useDelimiter("\n"); You don't need this!
 String tmp[];
 int line=0; //number of lines

 while(fileScanner.hasNext()) {
     line++; 

     //this returns the entire line, that's why you don't need useDelimeter()
     //it also splits it on '.' I'm not sure if that needs to be escaped but
     //just to be sure
     tmp=fileScanner.nextLine() . split(Pattern.quote("."));  

     baseArrayList.add(new test(line, tmp));

 }

fileScanner.close();

Here I use test to store the objects you read, I'm not sure what Base is supposed to be.

rath
  • 3,655
  • 1
  • 40
  • 53
0

A Java Bean/construct is required that will hold the day and the item together. The following code will read the text file. Each line will be converted to a List where finally the application will populate the List DayItems collection properly.

public class DayItem {

private int day;
private String item;

public int getDay() {
    return day;
}
public void setDay(final int day) {
    this.day = day;
}
public String getItem() {
    return item;
}
public void setItem(final String item) {
    this.item = item;
}
}

And main code

public class ReadFile {

private static final List<DayItem> dayItems = new ArrayList<DayItem>();

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

    final BufferedReader bufferReader = new BufferedReader(new FileReader("items.txt"));

    int lineNumber=0;
    try
    {
        String currentLine;
        while ((currentLine = bufferReader.readLine()) != null) {
            lineNumber++;
            List<String> todaysItems = Arrays.asList(currentLine.split(":"));
            addItems(todaysItems,lineNumber);
        }

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

}

private static void addItems(final List<String> todaysItems,final int day){

    int listSize = todaysItems.size();
    for(int i=0;i<listSize;i++){
        String item = todaysItems.get(i);
        DayItem dayItem = new DayItem();
        dayItem.setDay(day);
        dayItem.setItem(item);
        dayItems.add(dayItem);

    }
}

   }
Rami Del Toro
  • 1,130
  • 9
  • 24