【问题标题】:Reading from .txt file and importing data into 2D arraylist从 .txt 文件中读取数据并将数据导入 2D 数组列表
【发布时间】:2016-02-24 04:36:56
【问题描述】:

我正在研究 Project Euler 问题 11: 在下面的 20×20 网格中,对角线上的四个数字被标记为红色。

(我没有包括数字只是为了让我的问题更容易理解。如果你想参考它,链接是https://projecteuler.net/problem=11

这些数字的乘积是 26 × 63 × 78 × 14 = 1788696。

在 20×20 网格中,同方向(上、下、左、右或对角线)四个相邻数字的最大乘积是多少?

我的问题是我想将此数据输入到二维数组列表中,但不确定如何。到目前为止,这是我的代码。我知道解决这个问题的方法可能不是那么好,但我仍在学习,正如你可以清楚地告诉的那样,所以此时并不真正关心改进代码并使其更简单或更短。我所需要的只是知道如何将它存储为 2D 数组列表,然后我相信我应该很好。

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

感谢您的所有帮助。

【问题讨论】:

    标签: java


    【解决方案1】:

    从技术上讲,二维 ArrayList 是 ArrayList 的 ArrayList:

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

    但是,在这种情况下,您可能希望使用这样的二维数组(这也是数组的数组):

    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*/;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多