0

How to make a scanner that checks if the first letter is a character between A-V and if the second character is a number between 1-20? Some examples are: '.B4', 'H10.', '**V1', 'L19*', 'M12', or 'N14'.

I'm kind a new to Java. Still learning it in school. I've followed the lessons for about half a year now.

Now I've got an assignment for school. It is about creating a text-based minesweeper. I succeeded in printing the board and placing the mines. But now I'm stuck on getting the right input.

  • If you use '*' in the scanner like * B4 or B4* it should mark a square.
  • If you use '.' in the scanner like .B4 or B4. it should unmark a square.
  • And if you enter B4 it should open.

But I can't get this done in a neat way. I've tried to make sub-strings of it to check if every character is the right one but after I did that my code was kind of chaotic and it didn't work as supposed to.

I've tried it like: "Example 3 : Validating vowels in: Validating input using java.util.Scanner" only I used a variable of the length of my board. So if the board was 10 by 10 it wouldn't go further than J10. But that didn't work either for me.

So I was hoping that you could help me solving this problem.

Community
  • 1
  • 1
user3473161
  • 157
  • 2
  • 14

1 Answers1

0

As this is an assignment, I'll just give you a guideline rather than actual code.

First, you need to get the input into some format. Consider reading the input in from the scanner and storing it into a string.

We can then make use of Java's String functions, a list of which can be found here. Try to find a function that could be useful, perhaps one that lets us get the character at a certain index.

We can then do checks on the string. First we check the first character (the character at index 0), we want to know if that is a letter from A-V. To do this we can do a check on the ASCII numbers. Assuming you just want capital letters, if we convert A to an int, then it will have the value 65. V has the value 86. All the numbers in between correspond to the ASCII values of the letters in between.

Thus we can do a check, convert the first character to an integer, let's call it x. If x >= 65 && x <= 86, then it's a letter we can care about.

Next, you need to do the number checking. For this, take a look at the function Integer.parseInt(String s). It takes a String and then converts it to an integer. You'll have to do some checks to see if it's >= 10 or <10.

Clark
  • 1,339
  • 1
  • 7
  • 18
  • Very convoluted way. Plus `parseInt()` will trow exceptions if the string does not represent a number, so you will need to catch them. – PM 77-1 Mar 28 '14 at 17:09
  • I suppose. But I wanted to avoid using regex to keep it relatively simple to understand. – Clark Mar 28 '14 at 17:14