开发者

how to i start back fresh after one round of voting, without having stored statistic data in it

开发者 https://www.devze.com 2023-02-10 00:51 出处:网络
/** * @(#)MTVSurvey.java * * * @author * @version 1.00 2011/1/13 */ import java.util.*; import java.util.InputMismatchException;
/**
 * @(#)MTVSurvey.java
 *
 *
 * @author 
 * @version 1.00 2011/1/13
 */

import java.util.*;    
import java.util.InputMismatchException;
public class testing {

       static Scanner input = new Scanner(System.in).useDelimiter("\r\n"); 

    public static void main(String[] args) throws Exception{
         int choice=0 , i = 0, songNumber=0 , k=0;
         String[] songName = new String[999];
         int[] songNumberA = new int[999];
         int[] vote = new int[999];
         int voteTotal =0;
         int winningSong =0;
         int choiceA =0;
         int maximum = 0;
         int index = 0;
         int[] votePercentage = new int[999];
         do
        {
        System.out.println("*****MTV Main Menu*****");
          System.out.println("[1] Create Voting");
           System.out.println("[2] Enter Votes");
           System.out.println("[3] Statistics");
           System.out.println("[4] Quit now");
          System.out.print("Select your choice>");

          try
          {
          choice = input.nextInt();
          }
          catch(InputMismatchException ime)// if input is not int
        {
         System.out.println("Error");
         input.nextLine();
        }

          System.out.println("");  
         switch(choice)
           {
             case 1:      
                       System.out.println("   *****MTV SubMenu*****");
                       System.out.print("Enter no.of songs for voting <0 to exit to Main Menu> :");

                       try
                       {
                       songNumber = input.nextInt();    
                       }
                       catch(InputMismatchException ime)// if input is not int
{
System.out.println("Error");
input.nextLine();
}


                   if (songNumber >-1 && songNumber < 1)
                   {
                     break;
                }
                    for (int n=0 ; n < songNumber ; n++)
                    {
                    System.out.print("Please enter song title>>>");
                    try
             开发者_如何学运维       {
                    songName[i] = input.next();
                    }
                    catch(InputMismatchException ime)// if input is not int
{
System.out.println("Error");
input.nextLine();
}
                    i++;
                    }
                    System.out.println(" ");
                    System.out.println("These are the songs available for voting");
                    for (int j = 0; j < songNumber ; j++)
                    {
                    System.out.println(songName[j]);
                    }

                    break;
         case 2:       
                       System.out.println("   ***** MTV SubMenu*****   ");     
                       System.out.println("**** Vote for your fav song *****");
                           for (int j = 0; j < songNumber ; j++)
                    {
                    System.out.println("<"+(j+1)+">"+songName[j]);
                    }
                       System.out.print("Enter the song number:");
                       try
                       {

                    songNumberA[i] = input.nextInt();
                       }
                       catch(InputMismatchException ime)// if input is not int
{
System.out.println("Error");
input.nextLine();
}
                    while (songNumberA[i] > songNumber)
                    {
                    System.out.println("");
                    System.out.println(" Please enter song numbers available only");
                    System.out.println("");
                    System.out.println("   ***** MTV SubMenu*****   ");     
                       System.out.println("**** Vote for your fav song *****");
                           for (int j = 0; j < songNumber ; j++)
                    {
                    System.out.println("<"+(j+1)+">"+songName[j]);
                    }
                       System.out.print("Enter the song number:");

                       try
                       {
                    songNumberA[i] = input.nextInt();    
                       }
                       catch(InputMismatchException ime)// if input is not int
{
System.out.println("Error");
input.nextLine();
}

                    }
                    voteTotal++;
                    k = songNumberA[i] - 1;
                    vote[i]= 0;
                    if(vote[i] <= vote[k])
                    {

                    vote[k] = vote[k] + 1;

                    }    



                    System.out.println("<title>\t\t\t\t      Votes<%>\t      votes");
                    System.out.println("-------\t\t\t\t      --------\t      -----");
                    for (int j = 0; j < songNumber ; j++)
                    {
                    votePercentage[j]=(int)(((float)vote[j]/(float)voteTotal) * 100);
                    System.out.println("<"+(j+1)+">"+songName[j]+"\t\t\t\t"+votePercentage[j]+"          \t "+vote[j]);
                    }
                    i++;

                    break;
         case 3: System.out.println("<   Statistics Menu   >");
                 System.out.println("[1]Showtotal votes cast");
                 System.out.println("[2]Display winning song");
                 System.out.println("Press any other key to exit");
                 System.out.print("Enter your choice>");
                 try 
                     {

                 choiceA = input.nextInt();
                     }
                     catch(InputMismatchException ime)// if input is not int
{
System.out.println("Error");
input.nextLine();
}
                  switch(choiceA)
                  {
                  case 1: System.out.println("total votes casted="+voteTotal);
                  break;

                  case 2:
                      for (int w=0; w<= i; w++) 
                      {
                      if(vote[w] > maximum)
                      {
                          maximum = vote[w];
                          index = w;

                      }

                      }
                      System.out.println(songName[index]);
                      break;


                   default:System.out.println("Please enter <1 or 2> only!");
                           System.out.println("");

                             break;
                 }
                         break;
                 case 4: System.out.println("Thank you for using MTV System");
                         System.out.println("");
                         break;    
                 default:   System.out.println("Please enter 1-4 only!");
                            System.out.println("");
                            break;
           }
      }while(choice!=4);


}


}


Please mark this as homework if it's appropriate.

You're making the big mistake that all programmers make when they start out: you are not decomposing your problem. You've written line after line of code, shoved into a main method, and now you can't see your way through to make modifications or fix errors.

My advice is to break the problem into smaller methods that you can understand, develop, and test more easily. Build your solution up by calling those methods.

Sounds like one that you'd like is a reset() method that could set the voting back to zero.

Here's how I'd write it. Some of the stuff might not have been presented to you in your class yet, but you'll see what I mean about smaller methods. I didn't bother much with the menus that I know you want to present. I'm lazy, after all. I also simulated the voting with a random number generator for the same reason.

I ran it with these titles as input, taken from some web site:

"Black And Yellow" Grenade Firework "F**kin' Perfect" "I Need A Doctor"

Here are the results I got back:

    Black And Yellow 6 
             Grenade 5 
            Firework 3 
     F**kin' Perfect 3 
     I Need A Doctor 3 

Process finished with exit code 0

This is the source code:

package mtv;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * Survey
 * @author Michael
 * @since 2/13/11
 */
public class Survey
{
    private static final int MAX_VOTES = 200;

    private Map<Song, Integer> survey;

    public Survey(List<Song> songs)
    {
        this.survey = new HashMap<Song, Integer>();
        this.reset(songs);
    }

    public void reset(Collection<Song> songs)
    {
        for (Song song : songs)
        {
            this.survey.put(song, 0);
        }
    }

    public void vote(Song song)
    {
        int votes = 0;
        if (this.survey.containsKey(song))
        {
            votes = this.survey.get(song);
        }
        this.survey.put(song, ++votes);
    }

    public void sortByVote()
    {
        List<Map.Entry<Song, Integer>> list = new LinkedList<Map.Entry<Song, Integer>>(this.survey.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Song, Integer>>()
        {
            public int compare(Map.Entry<Song, Integer> o1, Map.Entry<Song, Integer> o2)
            {
                return (o1).getValue().compareTo(o2.getValue());
            }
        });

        Map<Song, Integer> result = new LinkedHashMap<Song, Integer>(this.survey.size());
        for (int i = list.size()-1; i >= 0; --i)
        {
            Map.Entry<Song, Integer> entry = list.get(i);
            result.put(entry.getKey(), entry.getValue());
        }

        this.survey = result;
    }

    public void print(PrintStream ps)
    {
        for (Song song : this.survey.keySet())
        {
            ps.printf("%20s %d %n", song, this.survey.get(song));
        }
    }

    @Override
    public String toString()
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);

        print(ps);

        return baos.toString();
    }

    public static void main(String[] args)
    {
        List<Song> songs = new ArrayList<Song>();
        for (String title : args)
        {
            songs.add(new Song(title));
        }

        Survey survey = new Survey(songs);

        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < MAX_VOTES; ++i)
        {
            int index = random.nextInt(songs.size());
            Song s = songs.get(index);
            survey.vote(s);
        }

        survey.sortByVote();
        System.out.println("Voting Results");
        survey.print(System.out);

        survey.reset(songs);
        System.out.println("Reset Survey");
        survey.print(System.out);
    }
}

class Song
{
    private String name;

    Song(String name)
    {
        this.name = name;
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o)
        {
            return true;
        }
        if (o == null || getClass() != o.getClass())
        {
            return false;
        }

        Song song = (Song) o;

        if (name != null ? !name.equals(song.name) : song.name != null)
        {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode()
    {
        return name != null ? name.hashCode() : 0;
    }

    public String toString()
    {
        return this.name;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消