If и Else Statments с использованием JOption Pane - PullRequest
0 голосов
/ 19 октября 2018

Здравствуйте, я новичок в java около месяца, как я начал.Я пытаюсь сделать мини-игру «Мини-Хэллоуин», в которой пользователь входит в дом и может выбрать для его изучения.Я пытаюсь сделать это через операторы if и else и панель JOption.Кажется, проблема в том, что JOptionPane.YES_OPTION всегда запускается, даже если я переименовал панели и пытаюсь получить доступ к различным панелям. Любой совет будет принят с благодарностью.

Ниже приведен код

private static int DiningRoom;
private static int livingroom;
private static int upStairs;





public static void main(String[] args) {
   JFormattedTextField nameField = new JFormattedTextField();
   ImageIcon iconic = new ImageIcon("HauntedHousemap.png");


   /* New JPanel */
  JPanel myPanel = new JPanel();
  myPanel.add(new JLabel("Enter your name to play: "));
  myPanel.add(nameField);
  myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));

  int result = JOptionPane.showConfirmDialog(null, myPanel, 
           "Enter Name", JOptionPane.OK_CANCEL_OPTION);
  if (result == JOptionPane.OK_OPTION) {   
  }

  JOptionPane.showMessageDialog(null,"Here is the Map!","Map",JOptionPane.INFORMATION_MESSAGE, iconic);

  JOptionPane livingRoomPane = new JOptionPane();
  JOptionPane startingPane = new JOptionPane();

  //***************************** STARTING OPTIONS **************************************//
  Object [] mainOptions = { "Living Room", "Dining Room", "Stairs" };
  Object [] StairsOptions = { "Bedroom1", "Beedroom2", "MasterBedroom"};
  Object [] DiningOptions = { "Kitchen", "Explore Items"};
  Object [] PantryOptions = { "Pantry", "Explore Items"};
  Object [] LivingOptions = { "Bathroom", "Explore Items"};
  Object [] Bathroom1stFloorOptions = { "Mirror", "Shower"};
  Object [] LivingRoomItems = { "Chest", "TV"};
  Object [] DiningRoomItems = { "Candelabra", "Table"};
  Object [] BedRoom1Items = { "Bathroom", "Explore Items"};
  Object [] BedRoom2Items = { "Bathroom", "Explore Items"};
  Object [] MasterBedRoomItems = { "Master Bathroom", "Explore Items"};



  //*********************************** User will choose where he wants to go from the front door **********************************//

  int startInput = startingPane.showOptionDialog(null, //Component parentComponent
                       ("Greetings " +  nameField.getText() + ", You are at the front door pick a path if you dare!"), //Object message,
                        "Haunted House", //String title
                       startingPane.YES_NO_OPTION, //int optionType
                       startingPane.INFORMATION_MESSAGE,  //int messageType
                       null,mainOptions, mainOptions [0]  ); //Icon icon, 

    //********************* IF PLAYER PICKED LIVING ROOM OUT OF STARTING OPTIONS ***************************************//
    switch (startInput) {
        case JOptionPane.YES_OPTION:
            System.out.println ("You are now in the living room");
            int livingRoom = JOptionPane.showOptionDialog(null, //Component parentComponent
                    ("Do you wish to go to the bathroom or explore the living room?"), //Object message,
                    "Haunted House", //String title
                    JOptionPane.YES_NO_OPTION, //int optionType
                    JOptionPane.INFORMATION_MESSAGE,  //int messageType
                    null,LivingOptions, LivingOptions [0]  );
            break;
        case JOptionPane.NO_OPTION:
            System.out.println ("You are now in the dinning room");
            int DiningRoom = JOptionPane.showOptionDialog(null, //Component parentComponent
                    ("Do you wish to go to the kitchen or explore the dining room?"), //Object message,
                    "Haunted House", //String title
                    JOptionPane.YES_NO_OPTION, //int optionType
                    JOptionPane.INFORMATION_MESSAGE,  //int messageType
                    null,DiningOptions, DiningOptions [0]  );
            break;
        default:
            System.out.println("You are now upstairs");
            int upStairs = JOptionPane.showOptionDialog(null, //Component parentComponent
                    ("Do you wish to go to Bedroom1, Bedroom2, or the Master Bedroom?"), //Object message,
                    "Haunted House", //String title
                    JOptionPane.YES_NO_OPTION, //int optionType
                    JOptionPane.INFORMATION_MESSAGE,  //int messageType
                    null,StairsOptions, StairsOptions [0]  );
            break; }




switch (livingroom) {
case JOptionPane.YES_OPTION: 
System.out.println ("You are now in the 1st floor Bathroom");
int bathRoomFloor1 = JOptionPane.showOptionDialog(null, 
               ("Do you wish to go to the bathroom or explore the living room?"), //Object message,
               "Haunted House", //String title
               JOptionPane.YES_NO_OPTION, //int optionType
               JOptionPane.INFORMATION_MESSAGE,  //int messageType
               null,Bathroom1stFloorOptions, Bathroom1stFloorOptions [0]  );
break;

default:
System.out.println ("You are now in the Exploring the living room");
int livingRoomExplore = JOptionPane.showOptionDialog(null, 
               ("Pick an Item to explore"), 
               "Haunted House", //String title
               JOptionPane.YES_NO_OPTION, //int optionType
               JOptionPane.INFORMATION_MESSAGE,  //int messageType
               null,LivingRoomItems, LivingRoomItems [0]  ); } 


switch (DiningRoom) {     
case JOptionPane.YES_OPTION: 
System.out.println ("You are now in the kitchen");
int kitchenFloor = JOptionPane.showOptionDialog(null, 
               ("Do you wish to go to the Pantry or explore the dining room?"),
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,PantryOptions, PantryOptions [0]  );
 break;
 default: 
 System.out.println ("You are now in the Exploring the dining room");
 int DiningRoomExplore = JOptionPane.showOptionDialog(null, 
               ("Pick an Item to explore"), 
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,DiningRoomItems, DiningRoomItems [0]  ); }

  switch (upStairs) {
  case JOptionPane.YES_OPTION: 
  System.out.println ("You are now in bedRoom1");
  int bedRoom1Explore = JOptionPane.showOptionDialog(null, 
               ("Do you want to go to the Bathroom or Explore the room?"), 
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,BedRoom1Items, BedRoom1Items [0]  ); 
 break;

  case JOptionPane.NO_OPTION: 
  System.out.println ("Do you want to go to the Bathroom or Explore the 
  room?");
  int bedRoom2Explore = JOptionPane.showOptionDialog(null, 
               ("Pick an Item"), 
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,BedRoom2Items, BedRoom2Items [0]  ); 
 break;
 default:
 System.out.println("You are now in the Master Bedroom");
 int masterBedExplore = JOptionPane.showOptionDialog(null, 
               ("Do you want to go to the Bathroom or Explore the room?"), 
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,MasterBedRoomItems, MasterBedRoomItems [0]  ); }

Проблема в том, что после 1-го комплекта IF и ElSE он всегда набирает:

«Вы находитесь в ванной на 1-м этаже», а остальные опции становятся очень переключенными и запутанными.

Буду признателен за любой совет.

Ответы [ 2 ]

0 голосов
/ 19 октября 2018

Использование полного шаблона State было бы намного лучше.Но вот пример, который значительно упростит текущий подход OP и значительно упростит отладку.Это устранит глубокую иерархию if / else (или switch) и может быть легко адаптировано / расширено.Это также значительно сокращает объем дублирующегося кода.

По сути, сохраняйте коллекцию всех возможных местоположений, а затем сохраняйте переменную состояния, в которой находится игрок.Отправка на основе текущего местоположения в конкретную комнату.Каждая комната устанавливает возможные ходы.

Этот код не является полным (не имеет всех комнат), и необходимо завершить перечисление, добавить действительный .toString () и т. Д., Но он показывает общий шаблон для простого кода OP.Кроме того, getAction может принимать дополнительный текст для отображения, заголовок может быть скорректирован с учетом текущей комнаты (потребуется параметр) и т. Д.

enum Locations
{
    FrontDoor, LivingRoom, DiningRoom, Stairs, Bedroom1, Bedroom2, MasterBedroom, Kitchen, Pantry, Bathroom, ExploreLivingRoomItems,

    // add a .toString() for each place
}



private static String getPlayer()
{
    JFormattedTextField nameField = new JFormattedTextField();

    /* New JPanel */
    JPanel myPanel = new JPanel();
    myPanel.add(new JLabel("Enter your name to play: "));
    myPanel.add(nameField);
    myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));

    int result = JOptionPane.showConfirmDialog(null,
                                               myPanel,
                                               "Enter Name",
                                               JOptionPane.OK_CANCEL_OPTION);


    if (result == JOptionPane.OK_OPTION) {
        return nameField.getText();
    }
    else {
        return "";
    }
}



private static void showMap()
{
    // show the map
}



private static Locations getAction(String playerName, Locations[] locations)
{
    Object[] opts = new Object[locations.length];
    for (int i = 0; i < opts.length; ++i) {
        opts[i] = locations[i].toString();
    }

    int res = JOptionPane.showOptionDialog(null,
                                           "Select your next move, "
                                                   + playerName,
                                           "Haunted House",
                                           JOptionPane.YES_NO_OPTION,
                                           JOptionPane.INFORMATION_MESSAGE,
                                           null,
                                           opts,
                                           opts[0]);

    return locations[res];
}



private static Locations getFrontDoor(String playerName)
{
    Locations[] locs = { Locations.LivingRoom, Locations.DiningRoom,
            Locations.Stairs };

    return getAction(playerName,
                     locs);
}



private static Locations getLivingRoom(String playerName)
{
    Locations[] locs = { Locations.Bathroom, Locations.ExploreLivingRoomItems };
    return getAction(playerName,
                     locs);
}



public static void main(String[] args)
{
    Locations loc = Locations.FrontDoor;


    final String playerName = getPlayer();
    showMap();


    boolean keepGoing = true;

    while (keepGoing) {

        switch (loc) {
        case FrontDoor:
            loc = getFrontDoor(playerName);
            break;

        case LivingRoom:
            loc = getLivingRoom(playerName);
            break;

        // all other rooms
        } // switch
    }


}

Enter NameFront Door Options Living Room Options

0 голосов
/ 19 октября 2018

Вместо того, чтобы использовать, если еще ... Используйте это

  switch(c) {   
case value1:        ...         break; 
case value2:        ...         break;  
case valueN:        ...     
default: }

Код более понятен для чтения ... так что вы понимаете, в чем проблема ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...