使用链表编写此Java网络程序。该程序添加与其联系的每个节点的详细信息,然后将其打印出来。在打印期间,我希望每次都将1添加到 Infor ,因为我将使用for循环打印细节10次。
此部分发生错误:
list.get(lastPostion).getInfor()+1;
以下是我的代码。
public class Linked {
public static void main(String[] args) {
workPls oks = new workPls();
try {
DatagramSocket socket = new DatagramSocket(Integer.parseInt(args[0]));
socket.setSoTimeout(0);
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
int data = 0;
PlsWork ok = new PlsWork(packet.getAddress(), "pc1", data);
oks.addNode(ok);
oks.print();
}
} catch (Exception error) {
error.printStackTrace();
}
}
}
public class PlsWork {
private InetAddress IP;
private String PC;
private int Infor;
public PlsWork(InetAddress IP, String PC, int Infor) {
this.IP = IP;
this.PC = PC;
this.Infor = Infor;
}
public InetAddress getIP() {
return IP;
}
public String getPC() {
return PC;
}
@Override
public String toString() {
return IP + " " + PC;
}
public int getInfor() {
return Infor;
}
}
public class workPls {
private LinkedList<PlsWork> list = new LinkedList<>();
private InetAddress ip;
private int lastPostion = 0;
public void addNode(PlsWork st) {
list.add(st);
}
public LinkedList getList() {
return list;
}
public void print() {
for (int i = 0; i > 10; i++) {
System.out.println(list);
System.out.println(list.get(lastPostion).getIP());
list.get(lastPostion).getInfor() + 1;
lastPostion+=1;
}
}
public InetAddress getip() {
return ip;
}
}
答案 0 :(得分:0)
list.get(lastPostion).getInfor() + 1
添加了两个int
s并且对结果不执行任何操作。要修改Infor
实例的PlsWork
实例变量,必须调用另一个方法。
向void setInfor(int newValue)
添加PlsWork
方法并致电:
PlsWork current = list.get(lastPostion);
current.setInfor(current.getInfor() + 1);
或者向void incrementInfor()
添加PlsWork
方法并致电:
list.get(lastPostion).incrementInfor();
另请注意,你的for循环中有一个不相关的拼写错误:
for (int i = 0; i > 10; i++)
应该是
for (int i = 0; i < 10; i++)