有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在一轮投票后重新开始,而不在其中存储统计数据

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


}


}

共 (1) 个答案

  1. # 1 楼答案

    如果合适的话,请把这个标记为家庭作业

    你犯了一个所有程序员一开始都会犯的大错误:你没有分解你的问题。您已经编写了一行又一行的代码,插入了一个main方法,现在您无法看到进行修改或修复错误的方法

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

    听起来你喜欢的一种方法是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;
        }
    }