Hi everybody I am trying to get values from an ArrayList I created. I have some indexes, and I want to print the data ONLY between the indexes I want, so far I ave done this, but it does not seem to work. I think the get() is not valid for want I want... Any ideas?
public static void main(String[] args) throws Exception {
Scanner dataSc = new Scanner(new FileReader("StudData1.txt"));
ArrayList<String> ArrayData = new ArrayList<String>();
ArrayList<String> idData = new ArrayList<String>();
ArrayList<String> idIndex = new ArrayList<String>();
int b = 0;
int a = 0;
int i = 0;
while (dataSc.hasNextLine()) {
String data = dataSc.nextLine();
ArrayData.add(i, data);
if (data.contains("ID: ")) {
idData.add(a, data);
idData.set(a, (idData.get(a).replaceAll("[\\D]", "")));
a++;
b++;
}
i++;
idIndex.add(b, Integer.toString(i));
}
int idSt1 = Integer.parseInt(idData.get(0));
int idSt2 = Integer.parseInt(idData.get(1));
int idSt3 = Integer.parseInt(idData.get(2));
int idxID1 = Integer.parseInt(idIndex.get(0));
int idxID2 = Integer.parseInt(idIndex.get(1));
int idxId3 = Integer.parseInt(idIndex.get(2));
if (idSt1 < idSt2 && idSt2 < idSt3) {
System.out.println(ArrayData.get(idxID1-3 , idxID2-3 );}
}
}
}
Its easy done with a for-loop.
for(int i = startindex+1; i<endindex; i++) {
System.out.println(ArrayData.get(i));
}
This loop will print all objects in the arraylist that are between the given indices.
But there is no method called get() which returns a collection of items that are between to given indices, you can only use the subList(arg0, arg1)
method to creat a subcollection and then iterate over this subcollection. Take a look at the Docs http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#get%28int%29
Example:
List<String> al = new ArrayList<>();
al.add("a");
al.add("b");
al.add("c");
al.add("d");
List<String> sublist = al.subList(0, 3); //inclusive index 0, exclusive index 3
for(String s : sublist)
System.out.println(s);
Output: a, b, c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With