I'm an extreme beginner, only a few days into learning, so sorry if this is an obvious question.
I'm trying to use ReadLine()
to get the user to enter a string (Rock, Paper or Scissors), then use an if statement to assign a variable of the same names a number 1-3 and then return to break out of the statement and then write the value in Main()
. I've done the first one here b/c no point doing the rest (again) if it doesn't work for one.
The error messages from VS Code are
There is no argument given that corresponds to the required formal parameter 'choice' of 'RockPaperScissors.Method()'
and
Not all code paths return a value
What am I forgetting/misunderstanding?
using System;
class RockPaperScissors
{
static int Method()
{
string playerString = Console.ReadLine();
int rock = 1;
if (playerString == "Rock")
{
int choice = rock;
return choice;
}
}
static void Main()
{
int Move = Method();
Console.WriteLine(Move);
}
}
CodePudding user response:
As it is mentioned in the error, your code handle only one use case, and it didn't return an integer for the rest of cases. This may help:
static int Method()
{
var playerString = Console.ReadLine();
switch (playerString)
{
case "Rock":
return 1;
case "Paper":
return 2;
case "Scissors":
return 3;
default:
// when the input data is not one of the previous strings
// it throws an exception so it should be catched and handled
throw new Exception("Not valid input");
}
}
CodePudding user response:
Or, making the code easier to read by using an enum
:
public enum HandSign
{
Rock, // rock beats scissors
Paper, // paper beats rock
Scissors, // scissors beats paper
}
Which allows this:
public static HandSign GetUserChoice()
{
HandSign result = default;
bool isCorrectEntry = false;
while (!isCorrectEntry)
{
Console.Write(@"Enter choice (Rock/Paper/Scissors): ");
var enteredText = Console.ReadLine();
isCorrectEntry = Enum.TryParse<HandSign>(enteredText, ignoreCase:true, out result);
}
return result;
}
Notice that it will prompt you over and over again until you spell scissors
correctly. It also ignores the case of the entered text.
CodePudding user response:
static int Method()
{
string playerString = Console.ReadLine();
int rock = 1;
if (playerString == "Rock")
{
int choice = rock;
return choice;
}
return rock;
}