【问题标题】:Is it possible to reuse a string in java?是否可以在java中重用字符串?
【发布时间】:2014-10-30 04:06:20
【问题描述】:

我正在尝试编写一个程序,我使用 UDP 客户端/服务器进行投票。客户端输入他们选择的候选人,将其发送到服务器,服务器记录候选人的投票,并为 25 个有效选票执行此操作。

输入第一个投票有效,但是,当输入其余投票时,我的问题出现了,因为我在 while 循环中使用相同的字符串来将客户端投票与数组中的一个字符串进行比较。 (不确定我是否解释清楚)

class UDPVoteServer {

public static final String[] candidates = new String[] {
    "Peter Singh",
    "Ricardo Allen",
    "Winston Alibocas",
    "Linda Jenkins", 
    "Marlene Williams"
};// 5 candidates to choose from

public static void main(String args[]) throws Exception {

    DatagramSocket serverSocket = new DatagramSocket(9816);
    System.out.println("UDP Server Started\n");
    byte[] receiveData = new byte[1024];
    byte[] sendData = new byte[1024];
    int maxVotes = 0; int hacked = 0;
while(true){

        int success = 0;  int invalid  = 0; int numVotes = 0;
        String canVote= "";

        int[] record = new int [5]; // records votes for each of the 5 candidates
        for(int i=0; i<5; i++) record[i] = 0;

        while (maxVotes < 25){

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);

            String clientIP = receivePacket.getAddress().getHostAddress();

            System.out.println("Received vote from client IP "+clientIP );

            /*block a hacker IP from trying to vote*/
            String blockedIP = "109.211.55.44";


            if (clientIP.equals(blockedIP)){
                System.out.println("\nRestricted IP contact made");
                InetAddress IPAddress = receivePacket.getAddress();

                int port = receivePacket.getPort();
                String error = "Your machine has been debarred from voting!";

                sendData = error.getBytes();

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
                serverSocket.send(sendPacket);

                 hacked++;
                 break; //exit loop if a blocked ip tries to access server

          }

        String VoterPick = new String(receivePacket.getData());//from client
        canVote = VoterPick.trim().replaceAll(" +", " "); //removes extra white spaces
        System.out.println(canVote);

        InetAddress IPAddress = receivePacket.getAddress();
        int port = receivePacket.getPort();
        String result= "";

            for(String pick : candidates) {

                for(int i=0; i<5; i++){

                if(canVote.equalsIgnoreCase(pick)){ //checks to see if voter spelt candidate name correctly after removing unnecessary white space
                    //Calculate voting here   

                    record[i] = numVotes + 1; //adds a vote to the respective candidate


                     result = "Vote Successful";
                    success++;
                maxVotes++; //increment only if the vote was successful; therefore loop stops when there are 25 valid votes entered
                    sendData = result.getBytes();
                    break;  
                }

                //if spelt wrong record it as an invalid vote
                else { 
                     result = "Invalid Candidate";
                    invalid++;
                    sendData = result.getBytes();
                    break;  
                }
                }
            }

            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

            serverSocket.send(sendPacket);

            //maxVotes++;
            //canVote = ""; //this does not seem to work

        }
        System.out.println("Hacker tried to access server " +hacked+ " times.");
        System.out.println("Successful votes: " +success);
        System.out.println("Invalid Votes: " +invalid +"\n");
        for(int i=0; i<5; i++) {
                System.out.println(candidates[i] + " " + record[i]);
        }
     }
  }

}

我正在尝试清除存储在字符串 canVote 中的信息,因此新的候选投票可以存储在字符串 canVote 中,但它似乎不起作用,因此即使客户端打印了无效的候选已正确输入。

是否可以重复使用字符串 canVote 或者是否有其他方式来存储信息?

感谢您提供的任何帮助。

【问题讨论】:

  • numVotes 除了 0 之外,从未分配任何值。我不确定我是否看到记录数组的点,因为每个元素最终都相同。
  • 记录数组是记录每个候选人获得的票数,以输出获胜者。然而那是未完成的代码,我试图在使程序更复杂和更难调试之前修复我的字符串问题。
  • 我知道它还没有完成,但这让我很困惑。为什么每个候选人都需要 5 票? 25张有效票是什么意思? 25个选民?我目前的猜测是您不需要静态 canVote 来清除它并重用它。帮助我理解代码背后的目的,我将能够提供帮助。也许在代码中添加一些 cmets?

标签: java string udp client-server reusability


【解决方案1】:

如果您想在函数调用之间保留 canVote 变量,您可以将其设为 static,但是您应该小心,如果没有额外的逻辑,它不会是线程安全的。

// static class variable
private static String canVote = "";

// reference in your method as...
MyClass.canVote = "something";

还有其他持久性数据存储选项,如数据库、memcached 等,但您需要再次考虑代码的线程安全性。

【讨论】:

  • 这是正确的答案(赞成)...改变了我的评论。误读了问题。继续。
【解决方案2】:

我不相信:

        for(String pick : candidates) {

            for(int i=0; i<5; i++){

                 if(canVote.equalsIgnoreCase(pick)){ //checks to see if voter spelt candidate name correctly after removing unnecessary white space

做你认为它做的事。

当确实有 5 个候选者时,这将循环 25 次,但对于每个候选者(名为 pick),它会检查相同的 canVote 5 次,在 record 数组的不同元素中记录相同的结果。

如果没有i 循环并在候选循环中增加i,你可能会更好。您需要一个持续到 25 票有效投票的外部循环。可能是 while 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-02
    • 2017-02-05
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2011-09-20
    相关资源
    最近更新 更多