扫描仪阅读

时间:2017-10-26 00:56:45

标签: java multidimensional-array

所以,我几乎完成了我的扫雷游戏,但我怎么做到这样我的扫描仪,如果读取“字符串”将作为一个句子回复。这是我的代码的一部分:

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int a = 0;
    int b = 0;
    String cont;

    System.out.println("Welcome to Mine Sweeper!");

    do {
        a = promptUser(in, "What width of map would you like (3 - 20):", 3, 20);
        b = promptUser(in, "What height of map would you like (3 - 20):", 3, 20);

        char [][] map = new char [b][a];
        eraseMap(map);

        simplePrintMap(map);
        int c = promptUser(in, "row:", 1, a);
        int d = promptUser(in, "column:", 1, b);

        map[c- 1][d - 1] = Config.NO_NEARBY_MINE;

        simplePrintMap(map);

        System.out.println("Would you like to play again?(y/n)?");

        cont = in.next();
        in.nextLine();
     } while (cont.trim().indexOf("y") == 0);

     System.out.print("Thank you for playing Mine Sweeper!");
}

public static int promptUser(Scanner in, String prompt, int min, int max) {

    int userInput;

    System.out.println(prompt);
    userInput = in.nextInt();

    while (userInput < min || userInput > max){
        System.out.println("Expected a number from " + min + " to " + max + ".");
         userInput = in.nextInt();
     }

    return userInput;
}   

所以在我的promptUser方法中,它会要求游戏地图的宽度和高度的int值。但是,如果我想要回复“Expected a number ....”如果我写了一个字符串而不是int,我该怎么把它改成?

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是检查您的userInput是否仅包含使用正则表达式模式匹配的数字。

   String userInput = in.nextLine();
   if(userInput.matches("\\d+"))
   { 
       //use this as your input, it is an int (clearing up your confusion)
       int coOrd = Integer.parseInt(userInput);
   }
   else
   {
      //code block if false
   }