gpt4 book ai didi

java - 从文件读取然后创建私有(private)类的对象

转载 作者:行者123 更新时间:2023-12-01 22:45:40 28 4
gpt4 key购买 nike

我在公共(public)类 singleLinkedList 中有私有(private)类节点,并且我想从另一个公共(public)类移动列表(作为临时),那么我如何创建临时节点或(方法)来移动列表。我无法将类 Node 更改为公共(public),我应该保持私有(private)。编程的思想是:在 TextAnalyzer 类中从文件中读取数据,然后将其插入到 SinglyLinkedList 中并计算单词的频率。单链表类

   public class SinglyLinkedList<T> {
private static class Node<T> {
public T data;
Node<T> next;
public Node(T data) {
this.data = data;
next = null;
}
}
Node<T> head;
Node<T> tail;
int size;

public SinglyLinkedList() {
head = null;
tail = null;
size = 0;
}

public void insert(T S) {
Node<T> temp = new Node<T>(S);
if (head == null) {
head = tail = temp;
size++;
return;
}

temp.next = head;
head = temp;
size++;
return;
}

public void display() {
Node<T> tmp = head;
while (tmp != null) {
System.out.println(tmp.data.toString());
tmp = tmp.next;

}

TextAnalyzer 类

  SinglyLinkedList<WData> list = new SinglyLinkedList<WData>();
private static class WData {

String word;
int freq;

public WData(String w, int f) {
word = w;
freq = f;
}

// .. Add other methods here as needed
@Override
public String toString() {
// if(list.)
return "WData{" + "word=" + word + " , freq=" + freq + '}';
}
}
public Scanner sc;

public void processText(String filename) {

try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
String line = sc.next();
String[] st = line.split(" ");

for (int i = 0; i < st.length; i++) {

processWord(st[i]);
}}
list.display();
} catch (FileNotFoundException ex) {
System.out.println("error in loadstudends Scanner");
}
}
public void processWord(String word) {
Node<WData> temp = list.head;

while (temp != null) {
if (temp.data.word.equalsIgnoreCase(word)) {
break;
}
temp = temp.next;
}
if (temp == null || Dtemp.data.word.matches(".*\\d.*")) {

list.insert(new WData(word, 1));

} else {
temp.data.freq += 1;
}
}}

我们无法创建节点 temp,因为类节点是私有(private)的,所以我无法进行循环

最佳答案

您可能想要执行以下操作1. 在 SinglyLinkedList 中创建您自己的 Iterator 实现

public class MyIterator implements Iterator<T> {
private Node<T> next = head;
private Node<T> current = null;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
if (hasNext()) {
current = next;
next = current.next;
return current.data;
}
throw new NoSuchElementException();
}

@Override
public void remove() {
//TODO
}
}
  • 制作SinglyLinkedList来实现Iterable
  • public class SinglyLinkedList<T> implements Iterable<T> {
  • 调用 iterator() 时返回在 1 中创建的迭代器实例
  •   @Override
    public Iterator<T> iterator() {
    return new MyIterator();
    }
  • 用于文本分析器类中的每个循环
  • 关于java - 从文件读取然后创建私有(private)类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474738/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com