Vaerys_Dawn

Voting system

Sep 7th, 2016
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. public String addVote(String voterID, String vote) {
  2.     StringBuilder builder = new StringBuilder();
  3.     boolean userFound = false;
  4.     int position = -1;
  5.     ArrayList<String> userVotes;
  6.     ArrayList<String> newVotes = new ArrayList<>(Arrays.asList(vote.split(" ")));
  7.     for (int i = 0; i < voting.size(); i++) {
  8.         String[] testVotes = voting.get(i).split(",");
  9.         if (voterID.equals(testVotes[0])) {
  10.             position = i;
  11.             userFound = true;
  12.         }
  13.     }
  14.     if (userFound) {
  15.         userVotes = new ArrayList<>(Arrays.asList(voting.get(position).split(",")));
  16.     } else {
  17.         userVotes = new ArrayList<>();
  18.     }
  19.     if (userVotes.size() == Globals.voteLimit++) {
  20.         return "> You have already used up all of your votes.";
  21.     }
  22.     int x = 0;
  23.     builder.append("> Your votes for entries: \n");
  24.     for (int i = 0; userVotes.size() > i; i++) {
  25.         if (x < Globals.voteLimit) {
  26.             try {
  27.                 int entry = Integer.parseInt(newVotes.get(i));
  28.                 if (entry > Globals.compEntries) {
  29.                     builder.append("    **Vote Not counted. Reason: Number too high**\n");
  30.                 } else {
  31.                     userVotes.add(""+entry);
  32.                     builder.append("    Entry: **" + entry + "**\n");
  33.                     x++;
  34.                 }
  35.             } catch (NumberFormatException e) {
  36.                 builder.append("    **Vote Not counted. Reason: Not a number**\n");
  37.             }
  38.         }
  39.     }
  40.     if (newVotes.size() > Globals.voteLimit){
  41.         builder.append("    **Rest of Votes not counted: Reason Max votes = " + Globals.voteLimit + "**\n");
  42.     }
  43.     builder.append("    Have been saved.");
  44.  
  45.     StringBuilder finalVotes = new StringBuilder();
  46.     for (String s : userVotes){
  47.         finalVotes.append(s + ",");
  48.     }
  49.     finalVotes.delete(finalVotes.length()-1,finalVotes.length());
  50.     if (userFound){
  51.         voting.set(position,finalVotes.toString());
  52.     }else {
  53.         voting.add(finalVotes.toString());
  54.     }
  55.     return builder.toString();
  56. }
Advertisement
Add Comment
Please, Sign In to add comment