为什么客户端在Java中的这个测验实现中没有得到下一个问题?

x8goxv8g  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(83)

这段代码工作,因为while循环工作,但当我删除UserThread类中的此注解时

/*  for(Entry<Integer,List<String>> m: server.lista.entrySet()) {
                        if(c==m.getKey()) {
                        m.getValue().add(name);
                        //toUser.println("");
                    }
                    }
                    for(Entry<Integer,List<String>> m: server.lista.entrySet()) {
                        System.out.println(m.getKey()+" "+m.getValue());
                    }*/

客户端没有收到下一个问题。循环在这里停止。我能知道为什么会这样吗?代码在下面。

package quiz;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;

public class Server {
public static int test_port=12321;
private int port;
private int counter=0;
private int length;
BufferedReader fromDocument;
public int numberOfClients=0;
public static HashMap<Integer,List<String>> lista=new HashMap<Integer,List<String>>();

    public static void main(String[] args) {
        //int l=lengthHashMap();
        
        // TODO Auto-generated method stub
Server server=new Server(test_port);
int l=server.lengthHashMap();
for(int i=1;i<l;i++) {
    lista.put(i, null);
}
server.execute();
    }
private void execute() {
        // TODO Auto-generated method stub
        try(ServerSocket server=new ServerSocket(port)){
            
            while(true) {
                Socket client=server.accept();
                System.out.println("Client connected");
                numberOfClients++;
                UserThread user=new UserThread(client,this);
                user.start();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
public Server(int port) {
    this.port=port;
}
private int lengthHashMap() {
    try {
        fromDocument=new BufferedReader(new InputStreamReader(new FileInputStream("Questions.txt")));
        String line=fromDocument.readLine();
        while(line!=null) {
            counter++;
            line=fromDocument.readLine();
        }
        length=counter/5;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        return length;
    }

}
}
package quiz;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
import java.util.Map.Entry;

public class UserThread extends Thread{
    Socket client;
    Server server;
    BufferedReader fromDocument;
    private int counter=0;
    PrintWriter toUser;
    BufferedReader fromUser;
    String correctAnswer;
    String answer;
    String correctedLine;
    private int c=0;
    public UserThread(Socket client, Server server) {
        // TODO Auto-generated constructor stub
        this.client=client;
        this.server=server;
    }
public void run() {
    try {
        
        while(server.numberOfClients<2) {
            System.out.println();
        }
        
        fromDocument=new BufferedReader(new InputStreamReader(new FileInputStream("Questions.txt")));
        fromUser=new BufferedReader(new InputStreamReader(this.client.getInputStream()));
        toUser=new PrintWriter(this.client.getOutputStream(),true);
        String line=fromDocument.readLine();
        String name=fromUser.readLine();
        System.out.println(name);
                while(!line.equalsIgnoreCase("")) {
                    while(counter<5) {
                    counter++;
                    if(line.endsWith("*")){
                        correctAnswer=line.substring(0,1);
                        correctedLine=line.substring(0,line.length()-1);
                        toUser.println(correctedLine);
                    }
                    else {
                        toUser.println(line);   
                    }
                    line=fromDocument.readLine();

                }
                    c++;
                    counter=0;
                    answer=fromUser.readLine();
 
                        
                    
                    if(answer.equalsIgnoreCase(correctAnswer))
                        toUser.println("Correct!");
                    else
                        toUser.println("Incorrect!");
                    //line=fromUser.readLine();
                    //System.out.println(line);
                /*  for(Entry<Integer,List<String>> m: server.lista.entrySet()) {
                        if(c==m.getKey()) {
                        m.getValue().add(name);
                        //toUser.println("");
                    }
                    }
                    for(Entry<Integer,List<String>> m: server.lista.entrySet()) {
                        System.out.println(m.getKey()+" "+m.getValue());
                    }*/
                    
                    
    }
    } catch (Exception e) {
        // TODO: handle exception
    }
    
}
}
package quiz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
private String name;
private String hostname;
private int port;
String answer;
BufferedReader fromServer;
PrintWriter toServer;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
Client client=new Client("localhost",Server.test_port);
client.execute();
    }
private void execute() {
    try {
        this.setName();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        // TODO Auto-generated method stub
        try(Socket client=new Socket(this.hostname,this.port)){
            
            fromServer=new BufferedReader(new InputStreamReader(client.getInputStream()));
            toServer=new PrintWriter(client.getOutputStream(),true);
            System.out.println("Connected to server: "+this.hostname);
            toServer.println(this.name);
            String line;
            while(true) {
                for(int i=0;i<5;i++) {
                    line=fromServer.readLine();
                    System.out.println(line);
                }
                System.out.println("Your answer is: ");
                Scanner sc=new Scanner(System.in);
                answer=sc.nextLine();
                toServer.println(answer);
                line=fromServer.readLine();
                System.out.println(line);
                //toServer.println("Next");
                //for(int j=0;j<5;j++)
                //  line=fromServer.readLine();
            }
            
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
public Client(String hostname,int port) {
    this.hostname=hostname;
    this.port=port;
}
private void setName() throws IOException {
    // TODO Auto-generated method stub
    System.out.println("Enter your name: ");
    BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    this.name=stdin.readLine();
}
}

文件Questions.txt的内容:

1. Ko je režirao film Kad jaganjci utihnu?
A) Robert Zemekis
B) Frenk Darabont
C) Džonatan Dem *
D) Rob Rajner
2. U kojoj državi se nalazi jezero Retba? 
A) U Senegalu * 
B) U Ugandi
C) U Gani 
D) U Nigeriji 
3. Kako se zove drugi studijski album grupe Zabranjeno pušenje?
A) Dok čekaš sabah sa šejtanom * 
B) Male priče o veliko ljubavi 
C) Pozdrav iz zemlje Safari 
D) Fildžan viška 
4. Pod kojom zastavom nastupa teniser Alehandro Davidovič Fokina? 
A) Pod zastavom Argentine 
B) Pod zastavom Rusije 
C) Pod zastavom Velike Britanije 
D) Pod zastavom Španije *
fkvaft9z

fkvaft9z1#

您的代码在m.getValue().add(name)行出现NullPointerException。此异常的根本原因是在Server类中。从Server类中观察以下代码:

for (int i = 1; i < l; i++) {
    lista.put(i, null);
}

将每个Integer与一个null值关联。现在,无论何时使用lista.get(1),它都会返回null。使用lista.get(1).add(name)时会发生什么?它抛出一个NullPointerException。这就是为什么m.getValue().add(name)抛出NullPointerException的原因,因为m.getValue()为null。

改进

你的代码充满了不好的做法。您应该避免使用它们,因为这会使代码更难调试,可读性更差,甚至会影响性能。以下是我观察到的一些事情:
1.您没有在UserThread类中打印堆栈跟踪。如果你这样做的话,你自己就能发现这个问题了。目前,catch块只是空的。

  1. port变量可以是final和static。服务器将在固定端口上工作,并且它作为一个整体与服务器相关联,而不是服务器对象的特定示例。因此,它可以是最终的和静态的。
    1.从finally block返回。这是一个非常糟糕的做法,原因有几个。您可以在网上搜索以了解更多信息。
    1.如果不引发异常,While语句无法完成。你的循环是无限的,它只能在异常发生时结束。您可以在客户端添加优雅的结尾。它可以在回答完所有问题后结束。
    可能还有其他一些小的改进,但我会保持简短的列表。
cyvaqqii

cyvaqqii2#

1. Ko je režirao film Kad jaganjci utihnu?
A) Robert Zemekis
B) Frenk Darabont
C) Džonatan Dem *
D) Rob Rajner
2. U kojo državi se nalazi jezero Retba?
A) U Senegalu *
B) U Ugandi
C) U Gani
D) U Nigeriji
3. Kako se zove drugi studijski album grupe Zabranjeno pušenje?
A) Dok čekaš sabah sa šejtanom *
B) Male priče o veliko ljubavi
C) Pozdrav iz zemlje Safari
D) Fildžan viška
4. Pod kojom zastavom nastupa teniser Alehandro Davidovič Fokina?
A) Pod zastavom Argentine
B) Pod zastavom Rusije
C) Pod zastavom Velike Britanije
D) Pod zastavom Španije *

内容不是英语,但格式清晰。正确答案用 * 标记。

相关问题