Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

java - How to get elements from a text file into a 2D array?

Image of .txt file I would like to put into a 2D array

Above is the.txt file I would like to put into a 2D array. So the 2D array needs to have 3 columns and the amount of rows is 4. In the 2D array I need the date in the format dd/mm/yyyy to be in column 1 of the array. The product name needs to be in column 2, ad quantity (the number) in column 3. I have no idea how to do this.

Furthermore, after it is in the array I need to sort the array via the quantity (3rd column of array) but have it's corresponding row move with it. So 21/01/2021,Pencils,5 being at the top and 21/01/2021,Speaker,2 being at the bottom. If anyone knows how I could do this too then that would be great.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This might work, or be an idea:

int[] yourArr = new int[4][3]
Scanner in = new Scanner(new File("your file name")); // instert file name

for(int i = 0; i < 4; i++){
    String line = in.nextLine();

    String[] elems = line.split(",");
    for(int j = 0; j < 3; j++){
       elems[j] = yourArr[i][j];
    }
}


// to sort the array:
Arrays.sort(yourArr, Comparator.comparingInt(o -> int(o[2])));


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...