浏览器历史系统中循环的java乘法
我猜,我一直在为一个项目编写web浏览器,我发现我无法使我的历史记录系统按预期工作,目前我发现我的历史记录项正在复制,我的历史记录在基于for-loop样式金字塔的会话之间复制,金字塔的大小是我上次会话访问的页面数的n-1:
页面重复|上次访问的页面
1 1
12 2
123 3
1234 4
每当我进入一个新页面时,就会调用此方法,并且上半部分中的if语句只运行一次,此时浏览器启动,用于从存储在其中的CSV文件恢复上一个会话的历史记录
代码应该在每次访问页面时创建一个jmenuitem,然后将其添加到jmenu中,这样做很好,但是,它还应该将链接添加到列表中。然后将该列表附加到csv以供存储
public class FileBar extends JMenuBar {
int tracker = 0;
File histPath = new File("history.csv");
JMenu history = new JMenu("History");
List<String> histStore = new ArrayList<String>();
public void createhistory(String webAddress) {
try {
List<String> histFeedback = new ArrayList<String>();
writer = new FileWriter(histPath, true);
if (tracker < 1) {
// system to retrieve information from csv file upon launch of program
}
JMenuItem button = new JMenuItem(webAddress);
history.add(button);
button.addActionListener(new ActionListener() {
// ...
});
histStore.add(webAddress);
int i = 0;
for (i = 0; i < histStore.size(); i++) {
writer.append(histStore.get(i));
writer.append(",");
}
writer.flush();
} catch (Exception e) {}
}
}
# 1 楼答案
好吧,我想这就是问题所在。每次访问页面时,您似乎都在CSV中的行中添加整个历史
我不知道
f.histStore
来自哪里,但我假设它是从CSV中的行创建的。因此,如果CSV中有5个地址,那么看起来f.histStore.size() == 5
因此,当您转到一个页面时,您将该地址附加到
f.histStore
:好的,到目前为止看起来不错。但随后,您将附加到最初从中读取的行中:
因此,您已将整个列表附加到现有列表中。所以这将导致一个重复的模式,就像这样,其中
a
、b
和c
是地址:如果是这样的话,有一个简单的解决方案:只将最后一个地址写入文件。将写循环替换为:
这样行吗?如果不是,什么是不正确的输出
# 2 楼答案
假设您的csv中出现了金字塔问题,那么您每次访问页面时都会将历史记录列表写入csv。您访问的第一个页面将把该页面附加到列表中,然后将其写入csv。您访问的第二个页面会将该页面附加到列表中,然后将完整列表写入csv,因为以下代码:
您要么需要覆盖csv中的行,要么只追加最近的项目