I have a text file with about 200 item numbers and descriptions, which is formatted like this (without the bullets):
- 1642 Pure wool t-shirt
- 613 Red laced shoes
- 3477 Blue hat with feather
- …
I am trying to read and store the items numbers and descriptions into respective arrays, which is delimited by space. My issues are:
- I want to ignore the spaces in the description.
- When I sort or delete items, I want to ensure that the description gets deleted as well.
Here’s what I have tried so far but getting ArrayIndexOutOfBoundsException error and I am not even sure if it will read the description properly:
private Scanner file;
private int item = 0;
private String desc = "";
private int[] itemArr = new int[200];
private String[] descArr = new String[200];
int n = 0;
public void openFile(){
try{
file = new Scanner(new File("inventory.txt"));
}
catch(Exception e){
System.out.println("file not found");
}
}
public void readFile(){
while(file.hasNextLine()){
if (file.hasNextInt()){
item = file.nextInt();
}
while(!file.hasNextInt() && !file.hasNextLine()){
desc = desc + file.next() + " ";
}
itemArr[n] = item;
descArr[n] = desc;
n++;
}
for (int i = 0; i < n; i++){
System.out.println(itemArr[i] + " " + descArr[n] + "\n");
}
System.out.println("Total Records (n): " + n);
}
Or is there a better way to do this? I’ve read some post about Patterns and Regex, but not sure how to use that either.
Thank you!
There is no protection on
nexceeding200. If there are more that 200 iterations of thewhileloop then:will throw an
ArrayIndexOutOfBoundsException.If the
intat the beginning of each line is unique you could use aMap<Integer, String>to store the data. This will not place a limit of200on the number of items that can be read from the file and if you selected aTreeMapas the implementation it would sort them (you can either accept the natural ordering ofIntegeror define you ownComparator). As suggested by sethu you could use aBufferedReaderto read the file.For example: