Java制作数字文件的2D列表对象

Java制作数字文件的2D列表对象,java,Java,我有一个金字塔形的数字,像 一, 2 3 3 4 5 我试图用文件中的数字填充2D Arraylist。我试图先填充一行数字,然后将该行添加到列中,但我找不到正确的输入测试来完成这项工作 ArrayList<Integer> rows = new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> columns = new ArrayList<ArrayList<Integ

我有一个金字塔形的数字,像

  • 一,
  • 2 3
    • 3 4 5
我试图用文件中的数字填充2D Arraylist。我试图先填充一行数字,然后将该行添加到列中,但我找不到正确的输入测试来完成这项工作

ArrayList<Integer> rows = new ArrayList<Integer>(); 
ArrayList<ArrayList<Integer>> columns = new ArrayList<ArrayList<Integer>>(); 
    try {
        Scanner s = new Scanner(new File("1.txt"));
        //while (s.hasNext()) {
            String a = s.next();
            String b = s.next();
            s.nextLine();

            while(s.hasNextLine()) {
                while(s.hasNextInt() ) { 
                // I want to say while( has more lines is true )
                // ( create a row of ints and append it to columns
                    rows.add(s.nextInt());

                    }   
                columns.add(rows);
                rows.clear();
            }   

    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
ArrayList rows=new ArrayList();
ArrayList columns=新的ArrayList();
试一试{
扫描仪s=新扫描仪(新文件(“1.txt”);
//而(s.hasNext()){
字符串a=s.next();
字符串b=s.next();
s、 nextLine();
而(s.hasNextLine()){
而(s.hasnetint()){
//我想说while(多行才是真的)
//(创建一行整数并将其附加到列中。)
添加(s.nextInt());
}   
列。添加(行);
行。清除();
}   
catch(filenotfounde异常){
e、 printStackTrace();
}
编辑:我添加的最后一行是[1,2,3,3,4,5],而不是[3,4,5],因为s.hasNextInt()在迭代时始终为true,
因此while(在.hasNextLine()中)只运行一次

快速浏览一下,我会说这一行是您的问题:
rows.clear();

您的
变量仍然指向它在添加到
之前指向的同一列表,因此如果清除它,那么您所做的就是将空的
数组列表
添加到

替换此行:

rows.clear();
为此:

rows = new ArrayList<>();
rows=newarraylist();

这样,
变量仍然指向一个空的、全新的
数组列表
,但它之前指向的
数组列表
就不存在了。

一个简单的方法是用
nextLine()
和字符串拆分替换
hasNextLine()
循环

因此,您将使用
nextLine()

ArrayList行;
ArrayList columns=新的ArrayList();
试一试{
扫描仪s=新扫描仪(新文件(“1.txt”);
而(s.hasNextLine()){
字符串[]temp=s.nextLine().split(“”);
行=新的ArrayList();
对于(stringi:temp)int.add(Integer.parseInt(i));
列。添加(行);
}
}
catch(filenotfounde异常){
e、 printStackTrace();
}

它不会改变我的输出,最后一行是[1,2,3,3,4,5],而不是[3,4,5],我应该把它添加到问题中。我的s.hasNextLine()只运行一次这也是我最后要做的。我想可能会有一个scanner函数或新的类型inputindect。我不确定您使用的是什么版本的Java,所以我没有建议使用API,但如果您知道您的文件不会太大,这也值得一看。