私は持っていArrayList<Group> listOfGroups
ます。
グループには 4 つのフィールドがありますString groupName, int lastActiveID, int firstID, String indicator
。listOfGroups 内のすべてのグループに関する情報を返すメソッドを作成したいと考えています。
これが私が試していることです:
String theList="";
for(Group gr:listOfGroups){
theList+=gr.groupName+" "+gr.lastActiveID+" "+gr.firstID+" "+gr.indicator+"\n";
}
System.out.print(theList);
return theList;
メソッドを呼び出すと、最初のグループに関する情報のみが取得され、2 番目の呼び出しでは 2 番目のグループに関する情報が返されます。\n 文字が原因ですか?
System.out.println(theList)
文字列の内容を確認するためだけにこれを配置すると、すべてのグループに関する情報が得られます。それはまさに私が帰りたいものです。
どうすれば修正できますか?
編集:サーバーとクライアントであるはずです。これは私のサーバーです:
package server;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args){
if(args.length!=1){
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int portNumber=Integer.parseInt(args[0]);
try(
ServerSocket serverSocket=new ServerSocket(portNumber);
Socket clientSocket=serverSocket.accept();
PrintWriter out=new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in=new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
){
String command;
String response;
NNTPProtocol protocol=new NNTPProtocol();
while((command=in.readLine())!=null){
response=protocol.processCommand(command);
out.println(response);
}
}
catch(IOException e){
e.getMessage();
}
}
}
NNTP プロトコルは次のとおりです。
package server;
import java.io.*;
import java.util.ArrayList;
public class NNTPProtocol {
ArrayList<Group> listOfGroups=new ArrayList<Group>();
Iterator it=listOfGroups.iterator();
static int curPos=0;
String processCommand(String command){
if(command.equalsIgnoreCase("list")){
return getListOfGroups();
}
else return null;
}
String getListOfGroups(){
if(listOfGroups.isEmpty()){
try{
DataInputStream in=new DataInputStream(new BufferedInputStream(
new FileInputStream(
"C:\\Users\\Ivo\\Documents\\NetBeansProjects\\"
+ "NNTPServerClient\\GroupsInfo.txt")));
String groupName;
while(!(groupName=in.readUTF()).equals("end")){
listOfGroups.add(new Group(groupName, in.readInt(),
in.readInt(), in.readUTF()));
}
}catch(FileNotFoundException e){}
catch(IOException e){}
}
String theList="";
for(Group gr:listOfGroups){
theList+=(gr.groupName+" "+gr.lastActiveID+" "+
gr.firstID+" "+gr.indicator+"\n");
}
System.out.print(theList);
return theList;
}
}
そして Group クラス:
package server;
public class Group {
String groupName;
String indicator;
int firstID;
int lastActiveID;
Group(String groupName, int firstID, int lastActiveID, String indicator){
this.groupName=groupName;
this.indicator=indicator;
this.firstID=firstID;
this.lastActiveID=lastActiveID;
}
}