潜水比赛 - Java计划

时间:2016-02-27 15:48:48

标签: java arrays joptionpane

我正在制作一项类似于网站上另一个问题的潜水比赛计划。该计划的目标是要求用户输入潜水员的姓名,七个评委分数和潜水的难度等级。输入该信息后,我将根据用户创建的Diver类创建Diver对象。然后使用insertDiver方法,我应该按顺序将潜水员添加到潜水员阵列中,以便最高的finalScore是第一个。我不应该对数组进行排序。使用JOptionPane showMessageDialog输出,按照从最高finalScore到最低finalScore的顺序显示排名。因为,我将数组对象传递给insertDiver方法,所以在完成该方法后数组已经死了。我试图让Diver []数组成为一个全局变量,但这些结果也不好。所以底线,我不知道如何通过最高的finalScore将潜水员添加到潜水员阵列,我也不知道如何显示结果。这是我到目前为止的代码:

import javax.swing.JOptionPane;

public class DivingCompetition
{


public static void main(String[] args)
{
  String[] choices = {"Add Diver/Scores", "View Diver Standings", "Search for a diver", "Exit Program"};
  String input = (String) JOptionPane.showInputDialog(null, "What do you want to do?", "Diving Competition", 
                 JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
  while(!input.equals("Exit Program"))
  {
     if (input.equals("Add Diver/Scores"))
        addDiver();
     else if (input.equals("View Diver Standings"))
        viewStandings();
     else if (input.equals("Search for a diver"))
        searchDiver();
     else
        System.exit(0);
     input = (String) JOptionPane.showInputDialog(null, "What do you want to do?", "Diving Competition", 
                 JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);      
  }
}
public static void addDiver()
{
  String scoreInvalid = "The score must be between 0 and 10";
  String difficultyInvalid = "The difficulty must be between 1.2 and 3.8";
  double[] scores = new double[7];
  int i = 0;
  String tempScore = "";
  String tempDifficulty = "";
  double realDifficulty = 0;
  double realScore = 0;
  int numScores = 0;

  String diverName = JOptionPane.showInputDialog("Please enter the diver's name:");
  while (numScores < 7)
  {
     tempScore = JOptionPane.showInputDialog("Please enter the seven judge's scores one at a time");
     realScore = Double.parseDouble(tempScore);
     while (realScore < 0 || realScore > 10)
     {
        JOptionPane.showMessageDialog(null, scoreInvalid, "Invalid Score", JOptionPane.WARNING_MESSAGE);
        tempScore = JOptionPane.showInputDialog("Please enter the corrected score");
        realScore = Double.parseDouble(tempScore);
     }

     scores[i] = realScore;
     i++;
     numScores++;
  }
  tempDifficulty = JOptionPane.showInputDialog("Please enter the difficulty rating of the dive");
  realDifficulty = Double.parseDouble(tempDifficulty);

  while (realDifficulty < 1.2 || realDifficulty > 3.8)
  {
     JOptionPane.showMessageDialog(null, difficultyInvalid, "Invalid Difficulty", JOptionPane.WARNING_MESSAGE);
     tempDifficulty =  JOptionPane.showInputDialog("Please enter the                 corrected difficulty rating of the dive");
     realDifficulty = Double.parseDouble(tempDifficulty);
  }
  Diver aDiver = new Diver(diverName, scores, realDifficulty);
  Diver[] dArray = new Diver[30];
  insertDiver(aDiver, dArray);             
}
public static insertDiver(Diver newElement, Diver[] diverArray)
{
  int addpos = 0;
  int currentSize = 0;

  if (diverArray[addpos] == null)
  {
     diverArray[addpos] = newElement;
     currentSize++;
     addpos++;
  }   
  else
     while (addpos < diverArray.length)
     {
        if (newElement.getFinalScore() > diverArray[addpos].getFinalScore())
        {
           diverArray[addpos] = newElement;
           currentSize++;
           break;
        }   
        else
           addpos++;
     }      
  if (addpos >= diverArray.length)
     diverArray[addpos] = newElement;
  else
  {
     currentSize++;
     for (int i = currentSize - 1; i > addpos; i--)
     {
        diverArray[i] = diverArray[i-1];
        diverArray[addpos] = newElement;
     }           

  }
for (int i = 0; i<diverArray.length; i++)
  {
     System.out.println(diverArray[i]);//just to see the contents of the array printed
  }

}
public static void viewStandings()
{

}
public static void searchDiver()
{

}    
}

这是我创建的Diver类:

public class Diver
{//begin class

private final double MULTIPLIER = 0.6;
private String diverName;
private double[] scores = new double[7];
private double difficulty, finalScore;
//---------------------------------------------------   
public Diver(String dN, double[] s, double d)
{
  setDiver(dN, s, d);
}
//---------------------------------------------------   
public String getName()
{
  return diverName;
}
//---------------------------------------------------   
public double getDifficulty()
{
  return difficulty;
}
//---------------------------------------------------
public double[] getScores()
{
  return scores;
}
//---------------------------------------------------   
public double getFinalScore()
{
  return finalScore;
}
//---------------------------------------------------   
public String toString()
{
  return "Diver Name: " + diverName + " Judge's Scores: " + scores +
         " Dive Difficulty: " + difficulty;
}
//---------------------------------------------------   
public void setDiverName(String name)
{
  diverName = name.toUpperCase();
}
//---------------------------------------------------   
public void setDifficulty(double diff)
{
   difficulty = diff;
}
//---------------------------------------------------   
public void setScores(double[] sc)
{
   for(int i=0; i < 7; i++)
     scores[i] = sc[i];
}
//---------------------------------------------------   
public void setDiver(String nme, double[] score, double dif)
{
  setDiverName(nme);
  setScores(score);
  setDifficulty(dif);
  computeFinalScore();  
}
//---------------------------------------------------
private void computeFinalScore()
{
  double smallest = scores[0];
  double largest = scores[0];
  double scoreSum = 0;

  for(int i=1; i< scores.length; i++)
  {
     if(scores[i] > largest)
        largest = scores[i];
     else if (scores[i] < smallest)
        smallest = scores[i];                 
  }

  for( double i : scores)
  {
     scoreSum += i;
  }

  finalScore =  (scoreSum - smallest - largest) * difficulty * MULTIPLIER;         
} 
//---------------------------------------------------   
}//end class

3 个答案:

答案 0 :(得分:2)

  1. 为Diver Class编写一个Comparator,然后你可以使用像TreeSet这样的集合,这将使你的生活变得轻松。
  2. 对于显示,您可以使用JTable。
  3. 以下是您的示例运行代码:

    import java.util.Comparator;
    import java.util.Set;
    import java.util.TreeSet;
    
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    
    public class DivingCompetition
    {
        static DiverComparator comp = new DiverComparator();
        static Set<Diver> divers = new TreeSet<Diver>(comp); 
    
        public static void main(String[] args)
        {
            String[] choices = {"Add Diver/Scores", "View Diver Standings", "Search for a diver", "Exit Program"};
            String input = (String) JOptionPane.showInputDialog(null, "What do you want to do?", "Diving Competition", 
                    JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
            while(!input.equals("Exit Program"))
            {
                if (input.equals("Add Diver/Scores"))
                    addDiver();
                else if (input.equals("View Diver Standings"))
                    viewStandings();
                else if (input.equals("Search for a diver"))
                    searchDiver();
                else
                    System.exit(0);
                input = (String) JOptionPane.showInputDialog(null, "What do you want to do?", "Diving Competition", 
                        JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);      
            }
        }
        public static void addDiver()
        {
            String scoreInvalid = "The score must be between 0 and 10";
            String difficultyInvalid = "The difficulty must be between 1.2 and 3.8";
            double[] scores = new double[7];
            int i = 0;
            String tempScore = "";
            String tempDifficulty = "";
            double realDifficulty = 0;
            double realScore = 0;
            int numScores = 0;
    
            String diverName = JOptionPane.showInputDialog("Please enter the diver's name:");
            while (numScores < 7)
            {
                tempScore = JOptionPane.showInputDialog("Please enter the seven judge's scores one at a time");
                realScore = Double.parseDouble(tempScore);
                while (realScore < 0 || realScore > 10)
                {
                    JOptionPane.showMessageDialog(null, scoreInvalid, "Invalid Score", JOptionPane.WARNING_MESSAGE);
                    tempScore = JOptionPane.showInputDialog("Please enter the corrected score");
                    realScore = Double.parseDouble(tempScore);
                }
    
                scores[i] = realScore;
                i++;
                numScores++;
            }
            tempDifficulty = JOptionPane.showInputDialog("Please enter the difficulty rating of the dive");
            realDifficulty = Double.parseDouble(tempDifficulty);
    
            while (realDifficulty < 1.2 || realDifficulty > 3.8)
            {
                JOptionPane.showMessageDialog(null, difficultyInvalid, "Invalid Difficulty", JOptionPane.WARNING_MESSAGE);
                tempDifficulty =  JOptionPane.showInputDialog("Please enter the                 corrected difficulty rating of the dive");
                realDifficulty = Double.parseDouble(tempDifficulty);
            }
            Diver aDiver = new Diver(diverName, scores, realDifficulty);
    
            divers.add(aDiver);
        }
        public static void viewStandings()
        {
            Object[][] rows = new Object[divers.size()][]; 
            int i = 0;
            for(Diver d : divers) {
                rows[i] = new Object[3];
                rows[i][0] = i+1;
                rows[i][1] = d.getName();
                rows[i][2] = d.getFinalScore();
                i++;
            }
                Object[] cols = {
                    "Rank","Name","Final Score"
                };
                JTable table = new JTable(rows, cols);
                JOptionPane.showMessageDialog(null, new JScrollPane(table));
    
        }
        public static void searchDiver()
        {
    
        }    
    }
    class DiverComparator implements Comparator<Diver> {
    
        @Override
        public int compare(Diver o1, Diver o2) {
    
            // TODO Auto-generated method stub
            return (int) (o2.getFinalScore() - o1.getFinalScore());
        }
    
    }
    

答案 1 :(得分:0)

程序退出,内存中没有数据可用。为了保持程序运行,你必须使用一个JFrame,或者在一个使用一个线程来保持应用程序活着。

答案 2 :(得分:0)

将这行代码移到班级的顶部:

public class DivingCompetition{
    static Diver[] dArray = new Diver[30];

    public static void main(String[] args){
    etc

虽然它不是最好的解决方案,但它更容易实现。您所遇到的问题是,在完成该方法之后,数组已经死了,因为局部变量应该在其父代码完成后死亡。如果您像这样声明数组,则可以从类中的任何位置访问它。

要添加更多潜水员,只需在dArray中搜索null为空的地方。

最后,为了使您的代码正常工作,您需要将insertDiver方法更改为:

public static void insertDiver(Diver newElement, Diver[] diverArray)

为了在之后放置潜水员,最后没有对数组进行排序,你必须在添加潜水员时实施一个简单的排序算法:

1)将第一个潜水员放在第一个位置。

2)比较第二个潜水员得分,如果比第一个更重要,将第一个驾驶员移动到阵列末端的一个位置,并将第二个驾驶员放在第一个位置。如果没有,将第二个潜水员放在第二个位置。

3)随后,对于每个新潜水员,你要做的是检查他们的分数是否高于阵列中其他人的分数,以及是否移动了一个和所有先前潜水员的分数较低的一个最终的位置,所以他们可以为新的潜水员腾出空间,高分比他们高。

f.e。我们想用这个顺序排序[12,45,34,78]:

12 -> [null,null,null,null]

45 -> [12,null,null,null]

34 -> [45,12,null,null]

78 -> [45,34,12,null]

      [78,45,34,12]