在JAVA中从txt字典文件中搜索单词
enter image description here我编写了一个程序,用于通过文本文件字典搜索单词的含义。我已经通过服务器端加载了字典。我试图通过客户端向服务器发送一个单词,并接收该单词对应的含义。从客户端发送的消息将是:“搜索”+“放弃”。“放弃”由字符串值字表示
问题是,当我试图使用“c.equals(word)”这个方法在字典中查找单词时,它不起作用。但当我将字符串值替换为“放弃”时,程序运行良好。有人能帮我解决这个问题吗
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException{
int port = 3000;
byte [] data = new byte[1024];
byte [] datas = new byte[1024];
String word = null;
String Message = null;
String clientMessage = null;
File f = new File("dictionary.txt"); //load the dictionary
Scanner s = new Scanner(f);
String c = null;
while(true) {
try {
System.out.println("Waitting for a coonection on port 3000");
DatagramPacket receivePacket = new DatagramPacket(data,data.length);
DatagramSocket serverSock = new DatagramSocket(port);
serverSock.receive(receivePacket);
InetAddress IPAddress = receivePacket.getAddress();
int por = receivePacket.getPort();
clientMessage = new String(receivePacket.getData());
Scanner client = new Scanner(clientMessage); //deal with the message send from client socket
Message = client.next(); //get the first token from the client message
if(Message.equals("Search")) { //determain the funtion
word = client.next(); //get the word that need to search through dictionary
while(s.hasNextLine()) {
String a = s.nextLine();
Scanner b = new Scanner(a); // Scan the line one by one represented by b
c = b.next(); // find the first word of each line
System.out.println(c); //print c
System.out.println(word); //print word
if(c.equals(word)) { //if the first word of that line match with the word(send from client)
System.out.println(a); //print out that particular line
break;
} else
System.out.println("b");
}
}
}
catch (IOException e)
{
System.out.printlin("Wrong");
}
}
}
}
如果你还有任何问题,请告诉我
下面是打印c和word的结果 A. 放弃 A- 放弃 Aa 放弃 土豚 放弃 Ab- 放弃 船尾 放弃 放弃 放弃 被遗弃的 抛弃
从结果中,我们可以发现有一段时间c和word都是“放弃”的
至于我从客户端传输到服务器的消息,我添加了发送消息为“搜索”+“放弃”
我结果的屏幕截图
共 (0) 个答案