对Array进行排序并将结果用于if语句

时间:2013-12-10 09:07:24

标签: java arrays sorting

该程序首先要求用户输入两个宠物名称。然后将按如下方式打印他们的愤怒等级:

Oh cool, Poodle is a very unique name!
Poodle is feeling tetchy!
Oh cool, Ollie is a very unique name!
Ollie is DANGEROUS RIGHT NOW!!!.

然后它将询问您是否愿意先照顾好友宠物。我在名为sort(...)的方法中完成了这个,这就是我被困住的地方。

我希望它执行代码的喂食/唱歌部分,如果用户在被要求时键入“是”,则首先发生在愤怒宠物的petInteraction(...)中,如果没有,则执行代码照常。

以下是我正在使用的完整代码:

import javax.swing.*;

import java.util.Arrays;
import java.util.Random;
public class alientpetprogram
{

public static void main(String[] args)
{   
    //Generates a random value from 1-10 for the pet's emotional state
    int[] EmotionalState = new int [3];
    Random emotion = new Random();
    for(int i = 0; i <= 2; i++)
    {
    int hungerLVL = emotion.nextInt(10) + 1;
    EmotionalState[0] = hungerLVL;

    int thirstLVL = emotion.nextInt(10) + 1;
    EmotionalState[1] = thirstLVL;

    int irritabilityLVL = emotion.nextInt(10) + 1;
    EmotionalState[2] = irritabilityLVL;
    }

    String [] petName = new String [2];

    petEmotion(EmotionalState, petName);      
    System.exit(0);
} //ENDS main

    public static String[] petInteraction(int[] EmotionalState, String [] petName) //Use this further on in petEmotion()
    {
        for(int i = 0; i < 2; i++) //A for loop is used to store two pet's in an array. An emotional state is then assigned to the pet.
        {
            petName[i] = JOptionPane.showInputDialog("What is your pet called?");
            System.out.println("Oh cool, " + petName[i] + " is a very unique name!");

            if (EmotionalState[0] == 1 || EmotionalState[0] == 2 || EmotionalState[0] == 3)
            {
                System.out.println(petName[i] + " is feeling Calm.");
            }
            else if (EmotionalState[0] == 4 || EmotionalState[0] == 5 || EmotionalState[0] == 6 )
            {
                System.out.println(petName[i] + " is feeling tetchy!");
            }
            else if (EmotionalState[0] == 7 || EmotionalState[0] == 8 || EmotionalState[0] == 9 || EmotionalState[0] == 10 )
            {
                System.out.println(petName[i] + " is DANGEROUS RIGHT NOW!!!.");
            }
                EmotionalState[0] = (int)(Math.random()*0+9);

        }   
        sort(EmotionalState, petName);
        return petName;
    } //ENDS petInteraction

    public static void sort(int[] EmotionalState, String [] petName)
    {
        Arrays.sort(EmotionalState);
        for (int SortAnger = 0; SortAnger < EmotionalState.length; SortAnger++)
        {
            String carePet = JOptionPane.showInputDialog("Would you like to take care of the angrier pet first?");
            if(carePet.equalsIgnoreCase("Yes"))
            {

            }
            else if(carePet.equalsIgnoreCase("No"))
            {

            }
            System.out.println(""+ EmotionalState[SortAnger]);
        }


    }   

                public static void petEmotion(int[] EmotionalState, String [] petName) 
                {  
                      String[] petsName = petInteraction(EmotionalState, petName);

                      String userinput;
                      userinput=JOptionPane.showInputDialog("choose how many rounds?"); //Allows the user to set the rounds
                      int roundsuggestion=Integer.parseInt(userinput);

                        for (int round =1; round <=roundsuggestion; round++) //sets the amount of rounds the game runs for.           
                        {
                        System.out.println("Round " + roundsuggestion);                   
                        System.out.println(petsName[0] + "'s irrtability level is " + EmotionalState[2]);
                        System.out.println(petsName[0] + "'s thirst level is " + EmotionalState[1]);
                        System.out.println(petsName[0] + "'s hunger level is " + EmotionalState[0]); 

                        EmotionalState[0] = (int)(Math.random()*0+9);
                        EmotionalState[1] = (int)(Math.random()*0+9);
                        EmotionalState[2] = (int)(Math.random()*0+9);

                        System.out.println(petsName[1] + "'s irrtability level is " + EmotionalState[2]);
                        System.out.println(petsName[1] + "'s thirst level is " + EmotionalState[1]);
                        System.out.println(petsName[1] + "'s hunger level is " + EmotionalState[0]);   

                  //The for loop below is used to reduce the Thirst, Hunger and Irritability levels for pet one and two
                       for(int y=1; y<=2; y++)
                       {

                            String askToReduceIrritable = JOptionPane.showInputDialog("Would you like to sing for " + petsName[0]  + " in order to lower the pets irritability level?");

                            if (askToReduceIrritable.equalsIgnoreCase("Yes"))
                            {
                                EmotionalState[2] = EmotionalState[2] - 1;
                                System.out.println(petsName[0] + "'s irrtability level is now " + EmotionalState[2]);                           
                            }   

                            String askToReduceThirst = JOptionPane.showInputDialog("Would you like to give " + petsName[0] + " some water in order to reduce the thirst level?");

                            if (askToReduceThirst.equalsIgnoreCase("Yes"))
                            {
                                EmotionalState[1] = EmotionalState[1] - 1;
                                System.out.println(petsName[0] + "'s thirst level is now " + EmotionalState[1]);                           
                            }   

                            String askToReduceHunger = JOptionPane.showInputDialog("Would you like to give " + petsName[0] + " some food in order to reduce the hunger level?");

                            if (askToReduceHunger.equalsIgnoreCase("Yes"))
                            {
                                EmotionalState[0] = EmotionalState[0] - 1;
                                System.out.println(petsName[0] + "'s hunger level is now " + EmotionalState[0]);                           
                            }           
                            System.out.println("");
                            System.out.println("You will now take care of the second pet");

                            String askToReduceIrritableTwo = JOptionPane.showInputDialog("Would you like to sing for " + petsName[1]  + " in order to lower the pets irritability level?");

                            if (askToReduceIrritableTwo.equalsIgnoreCase("Yes"))
                            {
                                EmotionalState[2] = EmotionalState[2] - 1;
                                System.out.println(petsName[1] + "'s irrtability level is now " + EmotionalState[2]);                           
                            }   

                            String askToReduceThirstTwo = JOptionPane.showInputDialog("Would you like to give " + petsName[1] + " some water in order to reduce the thirst level?");

                            if (askToReduceThirstTwo.equalsIgnoreCase("Yes"))
                            {
                                EmotionalState[1] = EmotionalState[1] - 1;
                                System.out.println(petsName[1] + "'s thirst level is now " + EmotionalState[1]);                           
                            }   

                            String askToReduceHungerTwo = JOptionPane.showInputDialog("Would you like to give " + petsName[1] + " some food in order to reduce the hunger level?");

                            if (askToReduceHungerTwo.equalsIgnoreCase("Yes"))
                            {
                                EmotionalState[0] = EmotionalState[0] - 1;
                                System.out.println(petsName[1] + "'s hunger level is now " + EmotionalState[0]);                           
                            }           
                            String exitGame = JOptionPane.showInputDialog("Would you like to exit the game? Type yes/no");

                            if (exitGame.equalsIgnoreCase("Yes"))
                            {
                                System.exit(0);                       
                            }
                            else
                            System.out.println("");
                            JOptionPane.showMessageDialog(null, "A new round has begun!");

                        } // END second loop
           } // END first loop
                }//ENDS petEmotion                 

} //ENDS Class alientpetprogram

2 个答案:

答案 0 :(得分:0)

您需要将状态与宠物名称相关联。我建议您创建一个具有名称及其情绪状态的类Pet,以实现Comparable界面,以便您轻松排序一系列的宠物根据他们的愤怒状态。

public class Pet implements Comparable<Pet> {
   private String name;
   private int state;

   // Add required basic methods here

   int compareTo(Pet pet) {
      return state - pet.getState();
   }
}

然后将数组定义为:

Pet pets[] = // Initialize with Pet objects

然后按照您的方式对数组进行排序:

Arrays.sort(pets);

现在数组中的第一个对象将是最令人讨厌的宠物,你可以使用适当的类getter方法轻松提取他的名字。

答案 1 :(得分:0)

好的,我改变了一些东西,从这里开始,我希望你知道应该采取哪个方向。 :) 现在还有错误,你必须解决它们。如果你有两只宠物,你为什么要处理3种情绪状态?在创建宠物后,你不应该使用emotionState(java惯例的第一个小写字母)数组,并给它们提供情感状态。

只是一些额外的信息:Java是一种Object-Oriented Programming语言,因为您可以将实际对象表示为类(因此通过new创建实例=对象)。这就是为什么应该使用额外的类Pet,因为你代表了它的真实世界。 :)(ofc不仅是我们世界中实际存在的东西,外星人也被允许:P)

下面是我到目前为止更改的代码,如开头所述,您必须修改整个代码,因为某些内容不再兼容了。

希望这有帮助!

班级Pet

public class Pet implements Comparable<Pet> {
private String name;
private int state;

/**
* @return Returns the state.
*/
public int getState()
{
  return state;
}

/**
* @param state The state to set.
*/
public void setState(int state)
{
   this.state = state;
}

public int compareTo(Pet pet) {
   return state - pet.getState();
}

/**
 * @return Returns the name.
 */
public String getName()
{
   return name;
}

/**
 * @param name The name to set.
 */
public void setName(String name)
{
   this.name = name;
}
 }

班级alientpetprogram

import java.util.Arrays;
import java.util.Random;

import javax.swing.JOptionPane;

public class alientpetprogram
{


 public static void main(String[] args)
{   
   //Generates a random value from 1-10 for the pet's emotional state
   int[] emotionalState = new int [3];
   Random emotion = new Random();
   for(int i = 0; i <= 2; i++)
   {
   int hungerLVL = emotion.nextInt(10) + 1;
   emotionalState[0] = hungerLVL;

   int thirstLVL = emotion.nextInt(10) + 1;
   emotionalState[1] = thirstLVL;

   int irritabilityLVL = emotion.nextInt(10) + 1;
   emotionalState[2] = irritabilityLVL;
   }

   //fill the array already with 2 pets
   Pet pets[] = new Pet[]{new Pet(), new Pet()};

   petEmotion(emotionalState, pets);      
   System.exit(0);
} //ENDS main

   public static Pet[] petInteraction(int[] emotionalState, Pet[] pets) //Use this further on in petEmotion()
   {

       for(int i = 0; i < 2; i++) //A for loop is used to store two pet's in an array. An emotional state is then assigned to the pet.
       {
           String tempPetName = JOptionPane.showInputDialog("What is your pet called?");
           pets[i].setName(tempPetName);
           pets[i].setState(emotionalState[i]);
           System.out.println("Oh cool, " + pets[i].getName() + " is a very unique name!");
       }   

       Arrays.sort(pets);

       String carePet = JOptionPane.showInputDialog("Would you like to take care of the angrier pet first?");
       if(carePet.equalsIgnoreCase("Yes"))
       {
          for(int i = 0; i < 2; i++) //A for loop is used to store two pet's in an array. An emotional state is then assigned to the pet.
          {
              if (emotionalState[0] == 1 || emotionalState[0] == 2 || emotionalState[0] == 3)
              {
                  System.out.println(pets[i] + " is feeling Calm.");
              }
              else if (emotionalState[0] == 4 || emotionalState[0] == 5 || emotionalState[0] == 6 )
              {
                  System.out.println(pets[i] + " is feeling tetchy!");
              }
              else if (emotionalState[0] == 7 || emotionalState[0] == 8 || emotionalState[0] == 9 || emotionalState[0] == 10 )
              {
                  System.out.println(pets[i] + " is DANGEROUS RIGHT NOW!!!.");
              }
                  emotionalState[0] = (int)(Math.random()*0+9);
          }  
       }
       else if(carePet.equalsIgnoreCase("No"))
       {
          for(int i = 0; i < 2; i++) //A for loop is used to store two pet's in an array. An emotional state is then assigned to the pet.
          {
              if (emotionalState[0] == 1 || emotionalState[0] == 2 || emotionalState[0] == 3)
              {
                  System.out.println(pets[i] + " is feeling Calm.");
              }
              else if (emotionalState[0] == 4 || emotionalState[0] == 5 || emotionalState[0] == 6 )
              {
                  System.out.println(pets[i] + " is feeling tetchy!");
              }
              else if (emotionalState[0] == 7 || emotionalState[0] == 8 || emotionalState[0] == 9 || emotionalState[0] == 10 )
              {
                  System.out.println(pets[i] + " is DANGEROUS RIGHT NOW!!!.");
              }
                  emotionalState[0] = (int)(Math.random()*0+9);
          }  
       }

       return pets;
   } //ENDS petInteraction


               public static void petEmotion(int[] emotionalState, Pet[] pets) 
               {  
                     pets = petInteraction(emotionalState, pets);

                     String userinput;
                     userinput=JOptionPane.showInputDialog("choose how many rounds?"); //Allows the user to set the rounds
                     int roundsuggestion=Integer.parseInt(userinput);

                       for (int round =1; round <=roundsuggestion; round++) //sets the amount of rounds the game runs for.           
                       {
                       System.out.println("Round " + roundsuggestion);                   
                       System.out.println(pets[0].getName() + "'s irrtability level is " + emotionalState[2]);
                       System.out.println(pets[0].getName() + "'s thirst level is " + emotionalState[1]);
                       System.out.println(pets[0].getName() + "'s hunger level is " + emotionalState[0]); 

                       emotionalState[0] = (int)(Math.random()*0+9);
                       emotionalState[1] = (int)(Math.random()*0+9);
                       emotionalState[2] = (int)(Math.random()*0+9);

                       System.out.println(pets[1].getName() + "'s irrtability level is " + emotionalState[2]);
                       System.out.println(pets[1].getName() + "'s thirst level is " + emotionalState[1]);
                       System.out.println(pets[1].getName() + "'s hunger level is " + emotionalState[0]);   

                 //The for loop below is used to reduce the Thirst, Hunger and Irritability levels for pet one and two
                      for(int y=1; y<=2; y++)
                      {

                           String askToReduceIrritable = JOptionPane.showInputDialog("Would you like to sing for " + pets[1].getName()  + " in order to lower the pets irritability level?");

                           if (askToReduceIrritable.equalsIgnoreCase("Yes"))
                           {
                              emotionalState[2] = emotionalState[2] - 1;
                               System.out.println(pets[0].getName() + "'s irrtability level is now " + emotionalState[2]);                           
                           }   

                           String askToReduceThirst = JOptionPane.showInputDialog("Would you like to give " + pets[1].getName() + " some water in order to reduce the thirst level?");

                           if (askToReduceThirst.equalsIgnoreCase("Yes"))
                           {
                              emotionalState[1] = emotionalState[1] - 1;
                               System.out.println(pets[0].getName() + "'s thirst level is now " + emotionalState[1]);                           
                           }   

                           String askToReduceHunger = JOptionPane.showInputDialog("Would you like to give " + pets[1].getName() + " some food in order to reduce the hunger level?");

                           if (askToReduceHunger.equalsIgnoreCase("Yes"))
                           {
                              emotionalState[0] = emotionalState[0] - 1;
                               System.out.println(pets[0].getName() + "'s hunger level is now " + emotionalState[0]);                           
                           }           
                           System.out.println("");
                           System.out.println("You will now take care of the second pet");

                           String askToReduceIrritableTwo = JOptionPane.showInputDialog("Would you like to sing for " + pets[1].getName()  + " in order to lower the pets irritability level?");

                           if (askToReduceIrritableTwo.equalsIgnoreCase("Yes"))
                           {
                              emotionalState[2] = emotionalState[2] - 1;
                               System.out.println(pets[1].getName() + "'s irrtability level is now " + emotionalState[2]);                           
                           }   

                           String askToReduceThirstTwo = JOptionPane.showInputDialog("Would you like to give " + pets[1].getName() + " some water in order to reduce the thirst level?");

                           if (askToReduceThirstTwo.equalsIgnoreCase("Yes"))
                           {
                              emotionalState[1] = emotionalState[1] - 1;
                               System.out.println(pets[1].getName() + "'s thirst level is now " + emotionalState[1]);                           
                           }   

                           String askToReduceHungerTwo = JOptionPane.showInputDialog("Would you like to give " + pets[1].getName() + " some food in order to reduce the hunger level?");

                           if (askToReduceHungerTwo.equalsIgnoreCase("Yes"))
                           {
                              emotionalState[0] = emotionalState[0] - 1;
                               System.out.println(pets[1].getName() + "'s hunger level is now " + emotionalState[0]);                           
                           }           
                           String exitGame = JOptionPane.showInputDialog("Would you like to exit the game? Type yes/no");

                           if (exitGame.equalsIgnoreCase("Yes"))
                           {
                               System.exit(0);                       
                           }
                           else
                           System.out.println("");
                           JOptionPane.showMessageDialog(null, "A new round has begun!");

                       } // END second loop
          } // END first loop
               }//ENDS petEmotion                 

} //ENDS Class alientpetprogram