2017-10-26 6 views
0

私は掃海試合の作成をほぼ終えましたが、スキャナが "文字列"を読むと特定の文として返答するようにするにはどうすればいいですか?ここに私のコードの一部です:スキャナの読者

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型の値を求めるだろう。しかし、もし私がintの代わりに文字列を書いた場合、 "期待された数字が...."と返信したいのであれば、どうすれば変更できますか?

+0

コードを正しくフォーマットしてください。それはそのままでは読みにくいです。 –

答えて

0

これを行う1つの方法は、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 
    } 
+0

これは正しく動作しませんか? –

+0

nextInt()の代わりにnextLine()を使用してユーザー入力を読み取ると、これは機能します。 – Jesse

+0

ちょっと疑問ですが、別の方法でパースを使用しないのですか? –