簡體   English   中英

從.txt文件讀取並將數據導入2D arraylist

[英]Reading from .txt file and importing data into 2D arraylist

我正在研究Euler項目問題​​11:在下面的20×20網格中,沿對角線的四個數字用紅色標記。

(我沒有包括數字,所以我的問題更容易理解。如果要引用它,鏈接為https://projecteuler.net/problem=11

這些數字的乘積為26×63×78×14 = 1788696。

在20×20網格中,相同方向(上,下,左,右或對角線)上四個相鄰數字的最大乘積是多少?

我的問題是我想將此數據輸入2D arraylist,但不確定如何。 到目前為止,這是我的代碼。 我知道解決這個問題可能不是一個好方法,但是,正如您可以清楚地知道的那樣,我仍在學習,因此,現在一點也不在乎完善代碼並使之更簡單或更短。 我所需要的就是知道如何將其存儲為2D arraylist,然后相信我應該會很好。

import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
@SuppressWarnings("unchecked")
public class main{
public static int row(ArrayList data){
    int product=1;//product of any four numbers in sequence across
    int max=0;//max product going across
    int item;//sets value of data
    int y=0;//counts position of data (1-4)
    int rownum;//number row
    int column;//number column
    Object num;//used to extract data from arraylist before converting into int
    for(column=0;column<16;column++){
        while(y<4){
            item=x+y;
            num=data.get(item);
            product*=(Integer) num;
            if (product>max){
                max=product;
            }
            y++;
        }
        product=1;
        y=0;
    }
    return max;
}

public static void main(String[] args){
    File path=new File("../numbers.txt");
    int word;//represents number column 
    int max;//max product of any four numbers in order
    int product=1;//max product of each individual way (across, down, diagonal)
    int line;//each individual number
    ArrayList data=new ArrayList();
    try{
        Scanner in=new Scanner(path);
        while (in.hasNextLine()){
            for(word=0;word<16;word++){//goes across a row
                line=in.nextInt();
                data.add(line);//adds file to arraylist
            }
        }
    }
    catch(Exception ex){

    }
    max=row(data);
    System.out.println(max);
}

感謝您所有的幫助。

從技術上講,二維ArrayList是ArrayList的ArrayList:

ArrayList<ArrayList<Integer>> numbers = new ArrayList<>();

但是,在這種情況下,您可能要使用這樣的2D數組(它也是數組的數組):

int[][] numbers = new int[20][20];

然后,您可以使用嵌套的for循環輸入數字:

for (int i=0; i<20; i++){
    for (int j=0; j<20; j++){
        numbers[i][j] = /*yadda yadda*/;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM