如何为类中的 ArrayList 赋值?

很长一段时间以来,我一直无法弄清楚为什么您似乎无法在不出错的情况下为 ArrayList 赋值。


第一个代码块是主要方法,它从文本文件中逐行获取并使用分隔符拆分行。第一个字符串作为 long 存储在一个变量中,然后其他 9 个字符串存储在一个 ArrayList 中。它对文件中的每一行执行此操作。


我已经多次调试这段代码,它表明数组正在获得正确的值。


问题是当代码到达它调用插入的部分时,我已经在代码中注释过了。


它首先创建节点,但是当它到达要将第一个 ArrayList 中的值添加到新创建的 ArrayList 的部分时,一切都中断了。for 循环停止正常运行,即使达到限制,它也会继续增加。


我决定省略我也用于这个项目的 BinaryTree 类,因为它可以正常工作。


那么我将如何正确分配来自我传递给 Node ArrayList 的 ArrayList 的值?


package assignment7;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.io.PrintWriter;

import static java.lang.Long.parseLong;

import java.util.Scanner;

import java.util.ArrayList;


public class Assignment7 {


    public static void main(String[] args) throws IOException {


    boolean headerLine = true;

    String firstLine = "";

    String catchLine;

    String token;

    long s_cid;

    ArrayList<String> Arr = new ArrayList<String>();

    Scanner delimS;

    int count = 0;

    BinaryTree snomedTree = new BinaryTree();


    try(BufferedReader br = new BufferedReader(new FileReader("Data.txt"))) {


        while ((catchLine = br.readLine()) != null) {


            for(int i = 0; i < 9; i++){


                Arr.add("");


            }


            if(headerLine){


                firstLine = catchLine;

                headerLine = false;


            }


            else{


                delimS = new Scanner(catchLine);

                delimS.useDelimiter("\\|");

                s_cid = parseLong(delimS.next());


                while(delimS.hasNext()){


                    token = delimS.next();

                    Arr.set(count, token);

                    count++;


                }

//运行到这里然后这个插入函数被调用


                  snomedTree.insert(new Node(s_cid, Arr));


            }


            Arr.clear();


        }

    }


    try (PrintWriter writer = new PrintWriter("NewData.txt")) {


        writer.printf(firstLine);

        snomedTree.inorder(snomedTree.root, writer);


    }

}


}




潇湘沐
浏览 416回答 2
2回答

守候你守候我

它现在完美无缺。我将 Node 类更改为:package assignment7;import java.util.ArrayList;import java.util.List;class Node {&nbsp; &nbsp; public long cid;&nbsp; &nbsp; public ArrayList<String> Satellite;&nbsp; &nbsp; public Node l;&nbsp; &nbsp; public Node r;&nbsp; &nbsp; public Node(long cid, ArrayList<String> Sat) {&nbsp; &nbsp; this.Satellite = new ArrayList<String>(Sat.subList(0, Math.min(9, Sat.size())));&nbsp; &nbsp; this.cid = cid;&nbsp; &nbsp; }}我还确保在每次迭代后将 main 中的“count”变量改回 0。

FFIVE

public Node(long cid, ArrayList<String> Sat) {&nbsp; &nbsp; this.Satellite = new ArrayList<String>();&nbsp; &nbsp; this.cid = cid;&nbsp; &nbsp; for(int i = 0; i < Sat.size()-1; i++){&nbsp; &nbsp; &nbsp; &nbsp; Satellite.add(Sat.get(i));&nbsp; &nbsp; }}这里 0<9 是错误的,你得到了什么错误?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java