如何填写if语句以查看是否输入了有效的方向

时间:2018-01-17 14:23:47

标签: java netbeans

这是我正在为学校写的一个程序,它是一个2D阵列冒险游戏。我需要空白if语句的帮助。它需要知道是否输入了有效的方向。我只是不确定从哪里开始。我也想这样做,因此有一定数量的钥匙可以进入上锁的房间。我在编码方面不是很有天赋,所以这看起来很麻烦,但我是最好的。我怎样才能做到这一点?

package hauntedhouse;
import java.util.Scanner;
public class HauntedHouse {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    Scanner c = new Scanner(System.in);

        String room[][] = new String[2][2];         // allocate 2 dimensional array of strings

        //This section of code fills the 2D array with room names
        room[0][0] = "Entry Hall";
        //code to fill the rest of the rooms here
        room[1][0] = "Dining Room";
        room[2][0] = "Master Bedroom";
        room[0][1] = "Storage [locked]";
        room[1][1] = "Grand Hall";
        room[2][1] = "Bedroom";
        room[0][2] = "Garage [locked]";
        room[1][2] = "Back Door";
        room[2][2] = "";



        int x = 0;  // the coordinates of the room to start
        int y = 0;

        String di = ""; // variable used to hold the direction they entered
            System.out.println("Theres a secret in this house,");
            System.out.println("go into the locked rooms to find"); 
            System.out.println("out what it is, have these two keys!");
        do {

            System.out.println("You are now in the " + room[x][y]);

            //this next loop will repeat until a valid direction is entered
            while (true) //this loop continues until the "break" statement is executed
            {
                System.out.println("Enter your direction");
                if () //figure this out!!
                {
                    break;          //exits while loop
                }
            } // end while (true)

            if (di.equals("W"))
            {
               y = y+1; 
            } else if (di.equals("A")) {
               x = x-1;                 
            } else if (di.equals("S")) {
               y = y-1;                 
            } else if (di.equals("D"))  {
               x = x+1;                              
            } else {
              //an illegal direction has been entered           
         }
   }
  while (x>=2); }// end when you make it to the locked room SOMEHOW

   } // TODO code application logic here

1 个答案:

答案 0 :(得分:0)

要验证2D数组,您只需使用.equals()函数

即可
 String room [][] = new String [2][2];
 room[0][0] = "Entry Hall";
 if(room[0][0].equals("Entry Hall")){
  System.out.println("Inside Entry Hall");
 }