Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k 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 Reply

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])));


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...