0
import java.util.Random;
import java.util.Scanner;

public class MineSweeper {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    boolean playAgain = true;

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

while (playAgain)   {
    final int MIN_SIZE = 3;
    final int MAX_SIZE = 20;
    final char NO_NEARBY_MINE = ' ';

    String errorWidth = "Expected a number from " + MIN_SIZE + " to " + MAX_SIZE + "\nWhat width of map would you like (" + MIN_SIZE + "-" + MAX_SIZE + "):";
    String errorHeight = "Expected a number from " + MIN_SIZE + " to " + MAX_SIZE + "\nWhat height of map would you like (" + MIN_SIZE + "-" + MAX_SIZE + "):";

    System.out.println("What width of map would you like (" + MIN_SIZE + "-" + MAX_SIZE + "):");
    int userWidth = promptUser(scnr, errorWidth, MIN_SIZE, MAX_SIZE);
    System.out.println("What height of map would you like (" + MIN_SIZE + "-" + MAX_SIZE + "):");
    int userHeight = promptUser(scnr, errorHeight, MIN_SIZE, MAX_SIZE);

    String errorGetRow = "Expected a number from " + 1 + " to " + userWidth + ".";
    String errorGetCol = "Expected a number from " + 1 + " to " + userHeight + ".";
    int minRowCol = 1;

    char[][] mineArray = new char[userHeight][userWidth];
    eraseMap(mineArray);
    simplePrintMap(mineArray);

    System.out.println("row: ");
    int row = promptUser(scnr, errorGetRow, minRowCol, userWidth);
    System.out.println("column: ");
    int column = promptUser(scnr, errorGetCol, minRowCol, userHeight);
    mineArray[row-1][column-1] = NO_NEARBY_MINE;
    simplePrintMap(mineArray);

    System.out.println("Would you like to play again (y/n)?");
    String response = scnr.next();
    if (response.startsWith("Y") || response.startsWith("y")) {
            playAgain = true;
    }
    else {
        playAgain = false;
    }

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

public static int promptUser(Scanner in, String prompt, int min, int max) {
    int userTempVal = 0;

        do {
        userTempVal = in.nextInt();
            if (userTempVal < min || userTempVal > max) {
            System.out.println(prompt);
            }

       }while (userTempVal < min || userTempVal > max);

    return userTempVal; 
    }

public static void eraseMap(char[][] map) {
    final char UNSWEPT = '.';
    for (int row = 0; row < map.length; row++) {
        for (int col = 0; col < map[row].length; col++) {
            map[row][col] = UNSWEPT;
        }
    }
    return;
}    

public static void simplePrintMap(char[][] map) {
    for (int row = 0; row < map.length; row++) {
        for (int col = 0; col < map[row].length; col++) {
            System.out.print(map[row][col] + " ");
        }
        System.out.println("");
    }
    return; //FIXME
}

EDIT: So I changed my code to utilize .equals rather than ==, and my code works successfully when I input a string with only one word, so "Yes". If I input a string of multiple words ("Yes I do"), I get an error still. Typing a string with multiple words yields an error. When I use scnr . next(), it always compiles the else statement, even if the statement is "Yes I do", where the first letter is Y. If I use scnr . nextLine() it compiles the if statement, restarts the loop, prints "What width of map..." and then gives an error before I can input anything.

I'm referring mainly to the main method at the bottom from "Would you like to play again" to the end of the main method. I'm also having an issue in my promptUser method, where I want the method to display the error message and scan again for an int if the user enters anything besides an int.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
punchkey
  • 81
  • 1
  • 11
  • `java.lang.StringIndexOutOfBoundsException: String index out of range: 1` – punchkey Oct 25 '17 at 01:07
  • 2
    Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). To make it even more readable, one can use [`String.equalsIgnoreCases(...)`](https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String-). – Turing85 Oct 25 '17 at 01:14
  • @punchkey you may edit also your question to provide more information clearer. – Alex Oct 25 '17 at 01:32
  • Oh, you should keep your question here, for others to know how to fix if they face the same problem. – Alex Oct 25 '17 at 03:09
  • Don't vandalize your own question. If your found a solution on your own, post it as an answer. – gre_gor Oct 25 '17 at 03:32

3 Answers3

1

Use response.equals() instead of ==.

== compares references of objects, while equals() would compare values of the string.

miradham
  • 2,285
  • 16
  • 26
  • Despite the fact that this question is a duplicate and thus needs no separate answer, you should explain the difference. – Turing85 Oct 25 '17 at 01:17
  • I tried this and it only works if my string is just one word long. If i type "Yes I do", I still get an error: Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at MineSweeper.promptUser(MineSweeper.java:63) at MineSweeper.main(MineSweeper.java:27) – punchkey Oct 25 '17 at 01:21
  • @punchkey please read the question (and answers) I linked as duplicate. This should explain why your solution is not working and give you the necessary knowledge to implement miradham's suggestion correctly. – Turing85 Oct 25 '17 at 01:23
  • @punchkey as per exception you posted in your comment, it seems you are trying to read values. Try to use `hasNext` to avoid that. – miradham Oct 25 '17 at 01:30
  • @miradham how would I implement hasNext ? I've never used that before and am a bit confused. – punchkey Oct 25 '17 at 01:32
  • Are you trying to read int after reading response? If so read full line for response, i.e. `String response = scnr.nextLine();` Or you'd better to provide your full code. – miradham Oct 25 '17 at 01:38
1

You are facing this problem because you are using the == operator to compare strings. If you used the statement response.substring(0, 1).equals("Y"), that would fix the problem as this is the actual way to check equality of strings. Or you could use the less verbose method listed below.

public class main{
    public static void main(String[] args){
        String response = "Yello";
        char c = response.charAt(0);
        if(c == 'Y'){
            System.out.println("Do something");
        }
        else if(c == 'y'){
            System.out.println("Do another thing");
        }
    }
}

Simply take the first character of the string and check equality with any other character you want.

Crabigator360
  • 822
  • 10
  • 9
1

There are 2 problems with your code.

  1. Comparing String using ==

    It is wrong because it compares the object reference rather than the object content. You need to use String.equals() to compare. In your case, you can even use String.startsWith() to check if your input is starting with something.

  2. Use String.substring() on your input

    Since the user can input empty string by just press [ENTER], you cannot use String.substring(0,1) or otherwise you will get String index out of range.

To fix the above 2 problems, you may change your code like below.

// Read the whole line
String response = scnr.nextLine(); 
// change to upper case first and check the starting character
playAgain = (response.toUpperCase().startsWith("Y")); 

To make sure the next read is ready, I would suggest to add Scanner.nextLine() after finish reading on the current line.

e.g.

userTempVal = in.nextInt();
// add this line to consume the rest of the line
in.nextLine();
Alex
  • 803
  • 4
  • 9
  • I will edit my post to add my full code, because I keep getting weird errors even when I use the startsWith function. – punchkey Oct 25 '17 at 01:48
  • You should use `scnr.nextLine()` to read the whole line instead of just use `scnr.next()`. Use `scnr.next()` will only consume the first word and anything on the same line, even just an `[ENTER]`, will be left for the next `scnr.next()` or `scnr.nextInt()`. – Alex Oct 25 '17 at 02:02
  • When I use scnr.nextLine(), the program outputs "Would you like to play again...", then does not scan for an input and directly prints "Thank you for playing..." and closes the program. – punchkey Oct 25 '17 at 02:09
  • Note my edit, you should add also `in.nextLine()` to your other user input reading. – Alex Oct 25 '17 at 02:15