Hello, I’m working on this task:
Write a program that validates a battleship move. It first reads a letter [A–J] or [a–j] and then an integer [1–10], each from the new line. If the input for the move is valid, program should output “Next move is {letter}{number}.” Otherwise, it should output “Letter should be from A to J. Number from 1 to 10. Try again!” The program should continue to ask for and read values for the battleship move until the user inputs valid values for both of them. Pay attention: it should be case insensitive; ‘A’ and ‘a’ are both allowable. Your program should, however, output letter in the same case as it was entered. For example:
>a
>
Letter should be from A to J. Number from 1 to 10. Try again!
>10
>a
Letter should be from A to J. Number from 1 to 10. Try again!
>#
>10
Letter should be from A to J. Number from 1 to 10. Try again!
>c
>5
Next move is c5.
Here is my code:
namespace InputValidation
{
class Battleship
{
static void Main(string[] args)
{
var letterAsString = Console.ReadLine();
var numberAsString = Console.ReadLine();
char letter;
int number = 0;
bool valid = !char.TryParse(letterAsString, out letter) && !int.TryParse(numberAsString, out number);
while (valid)
{
if ( char.ToLower(letter) > 'j' || char.ToLower(letter) < 'a' || (number > 10) || (number < 1))
{
valid = false;
}
Console.WriteLine("Letter should be from A to J. Number from 1 to 10. Try again!");
letterAsString = Console.ReadLine();
numberAsString = Console.ReadLine();
}
Console.WriteLine($"Next move is {letter}{number}.");
}
}
}
Can anyone please help me to solve it?