2017-10-26 2 views
0

Also, ich bin fast fertig mit der Erstellung meines Minesweeping-Spiels, aber wie würde ich es so machen, dass mein Scanner, wenn eine "Zeichenfolge" liest, als ein bestimmter Satz antworten würde. Hier ist ein Teil meines Code:Scanner lesen

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; 
} 

So in meiner Methode des promptUser, es für einen int Wert der Breite und Höhe des Spielkarte fragen würde. Wenn ich aber wollte, dass "Expected a number ...." antwortete, wenn ich eine Zeichenfolge anstelle eines int schreiben würde, wie würde ich es dann ändern?

+0

formatieren Sie bitte Ihren Code richtig, es ist ziemlich schwer zu lesen, wie es ist. –

Antwort

0

Eine Möglichkeit, dies zu tun, wäre zu überprüfen, ob Ihr userInput nur Ziffern enthält, die reguläres Muster verwenden.

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

Also funktioniert das nicht richtig? –

+0

Dies funktioniert, wenn Sie nextLine() anstelle von nextInt() verwenden, um die Benutzereingabe zu lesen. – Jesse

+0

Ich frage mich nur, gibt es eine andere Methode, die parse nicht verwendet? –

Verwandte Themen