是否可以在java中重用字符串?

时间:2014-10-30 04:06:21

标签: java string udp client-server reusability

我正在尝试编写一个程序,我使用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,还是有其他方法来存储信息?

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

如果你想在函数调用之间保持canVote变量,你可以使它成为static,但是如果没有额外的逻辑,你应该警惕它不会是线程安全的。

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

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

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

答案 1 :(得分:1)

我不相信这一点:

        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个候选人足够肯定但是对于每个候选人(名为pick)时,它将循环25次,它检查相同的canVote 5次,在{{{的另一个元素中记录相同的结果1}}数组。

如果没有record循环,只需在候选循环中递增i,您可能会感觉更好。你需要一个持续到25个有效投票的外循环。可能是一个i循环。

相关问题