-5
/**
 * @(#)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);


}


}
4

1 回答 1

4

如果合适,请将此标记为家庭作业。

你犯了所有程序员刚开始时都会犯的大错误:你没有分解你的问题。你写了一行又一行的代码,塞进了一个主方法,现在你看不到修改或修复错误的方法。

我的建议是将问题分解为更容易理解、开发和测试的更小的方法。通过调用这些方法来构建您的解决方案。

听起来您想要reset()一种可以将投票设置回零的方法。

这就是我的写作方式。有些东西可能还没有在你的课堂上展示给你,但你会明白我所说的更小的方法是什么意思。对于我知道您想要展示的菜单,我并没有太在意。毕竟我很懒。出于同样的原因,我还使用随机数生成器模拟了投票。

我用这些标题作为输入运行它,取自一些网站:

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

这是我得到的结果:

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

Process finished with exit code 0

这是源代码:

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;
    }
}
于 2011-02-13T13:31:55.343 回答