0

So I have a file with a list like this

2134:193

192:1856

1092:1850

980:759

etc

i would like to process the file and add it to an array, then be able to grab the int's

like i would like to do System.out.println("first+" : "+second);

Not sure what the best way to store it is but here's my attempt so far

public static void loadList() {
    BufferedReader br = new BufferedReader(new FileReader("./data.txt"));
    String line;
    while ((line = br.readLine()) != null) {
        String args[];
        args = line.split(":");
        int first = Integer.toInt(args[0]);
        int second = Integer.toInt(args[1]);
        System.out.println(first + " : " + second);
    }
    br.close();
}
2
  • what is the problem in this ... you are doing good. ! just create arrays and put your data in it. I would recommend ArrayLists Commented Oct 11, 2013 at 23:40
  • i'm not sure how to store and grab the numbers is my issue :( i'm not good at arraylists Commented Oct 11, 2013 at 23:41

3 Answers 3

3

Try this :

Class

 Class DataClass
 {
   public int first; // Deliberately public 
   public int second;

   public DataClass(int val1, int val2){
   this.first = val1;
   this.second = val2;
   }
 }

Code

    public static void loadList() {

    ArrayList<DataClass> pairList = new ArrayList<DataClass>();
    BufferedReader br = new BufferedReader(new FileReader("./data.txt"));
    String line;
    while ((line = br.readLine()) != null) {
        String args[] = line.split(":");
        int first = Integer.valueOf(args[0]);
        int second = Integer.valueOf(args[1]);
        DataClass valPair = new DataClass(first,second);
        pairList.add(valPair);
        System.out.println(valPair.first + " : " + valPair.second);
    }
    br.close();
 }

Make sure you have proper try catch statements

Sign up to request clarification or add additional context in comments.

4 Comments

that's good - assuming there's no relationship between the first number in each pair and the second. Another collection class worth considering is Map.
Even if there is, Wont both will be put on the same Index in two lists.
as stated i'm not too familiar with arrays, i would like to call it, and if data is parsed properly, delete them from the array later in the method, want to grab numbers at random, first and second number should both be called at same time and removed at same time (they're a pair)
Then Edit your question to say that. This is not what your question meant at all ! The solution is to make a class i will edit my code
2

Doing a bit of Java-magic here:

  public static class DataValue {

    protected final int first, second;

    public DataValue(int first, int second) {
      this.first = first;
      this.second = second;
    }
  }

  public static List<DataValue> loadList() throws FileNotFoundException, IOException {
    final List<DataValue> result = new LinkedList<>();
    try (BufferedReader br = new BufferedReader(new FileReader("./data.txt"))) {
      String line;
      String args[];
      while ((line = br.readLine()) != null) {
        try {
          args = line.split(":");
          final int first = Integer.parseInt(args[0]);
          final int second = Integer.parseInt(args[1]);
          System.out.println(first + " : " + second);
          result.add(new DataValue(first, second));
        } catch (NumberFormatException | NullPointerException | ArrayIndexOutOfBoundsExceptione) {
          System.out.println("Unable to process line: " + line);
        }
      }
    }
    return result;
  }

First: this is Java 7 code, it doesn't work with Java 6.

  • One of the Object Oriented principle is: keep your data together. Therefore this approach above uses a special data holder class, to make sure you do not accidentally confuse numbers from different lines later on.

  • Using the try (stream) {} concept form Java 7 ensures that the stream is properly closed under all circumstances. In your code the stream would be left half-open if reading from it would cause an Exception to be thrown.

  • If you work with dynamic data from "outside", you must check it properly. You never know if anyone accidentally or on purpose put errors into the file. This is what my inner try-catch does.

  • Using an ArrayList is not a good idea in your case, because it has a fixed size and your data probably is not of a fixed size, therefore the internal storage would have to be re-created a few times during reading. A linked list performs perfectly in this case (but poorly if you do myList.get(index)).
    Later you can use the Java for-each loop like this:
    for (DataValue value : myList) { System.out.println(value.first + " : " + value.second); }

  • You should avoid to declare variables inside a loop unless you have to. And if you have to, use final to tell the JIT that it can use full optimization on these variables.

  • Integer.parseInt(string) is the correct way to transform a string into an Integer. Make sure to read the definition on when this throws an exception!

5 Comments

my goodness, the program i'm making doesn't need to be super efficient, there's no need for OOP, thank you for your contribution though, however I think it would be cleaner to just do final List<Integer, Integer> result = new LinkedList<>(Integer, Integer); result.add(first, second);
A List can only hold a single element, so List<int, int> is not possible with Java, this is solved by my DataValue class. In addition: if you code Java you code OOP, that is the very core of the language. ;)
If you don't want to use a Data Object, use a third part Pair implementation such as Java Tuples or Apache Commons Lang... Or better yet, use Scala ;).
how would i go about getting a random datavalue out and displaying it then removing from the list?
Travs, open a new question for it.
0

try this!

public static void loadList() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new FileReader("./data.txt"));
        String line;
        while ((line = br.readLine()) != null) {
            if(line.trim().length() == 0)
                continue;
            String args[];
            args = line.split(":");
            int first = Integer.parseInt(args[0]);
            int second = Integer.parseInt(args[1]);
            System.out.println(first + " : " + second);
        }
        br.close();
    }

1 Comment

How does this really differ from what the OP's attempt?

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.