This question already has answers here:
Input string was not in a correct format
(9 answers)
Closed 5 years ago.
Well, i've been having a problem with the code of a memory game. It is like a simon says but with numbers in C#.
The problem comes when, in the code, i use the Console Readkey to let the player make an input. But, the problem comes when i convert to int a number... It takes it like i had put a value that mismatched the type of data. Why does that happen=
public void playersTurn() {
for (int i = 0; i < 6; i++) {
if (!(failure)){
playerInput = Console.ReadKey().Key.ToString(); // if i put, for example, 5
Console.Write(playerInput); // it throws 5D50 (this was just to see if something weird was happening)
try{
playerNumber = Convert.ToInt32(playerInput);
}
catch(FormatException e){
Console.Clear();
Console.WriteLine("Solo numeros, chico"); // there is always an exception
}
Console.Write(playerNumber + " ");
if (playerNumber != thoseNumbers[i]) {
Console.WriteLine(" ");
Console.WriteLine("¡ERROR!");
failure = true;
}
}
thoseNumbers[i] = 0;
}
The convert method throws exception because it expects a number. If you pass it a string like 5D50 it will not know what to do with 'D' so it will throw exception.
Readkey() returns code of key, not the value the key is used for. Try this:
Convert.ToInt32(Console.Readline());
Related
This question already has answers here:
How to validate user input for whether it's an integer?
(10 answers)
Closed 4 years ago.
So i nearly have 2k lines of code and i have forgotten to / i do not know how to have input valdation on user inputs such as
cw("Hello Please Enter your age");
cw("If you are in a Group Input the Age of the Youngest Member of the Group.");
Age = Convert.ToInt32(Console.ReadLine());
I want to Make it so that users can enter only numbers and my program will not crash when they put in somthing els.
this is a common problem in the whole of my program for the console.readlines.
Is there a way on mass that i can introduce the input valdation for numbers only and letters only when approate?
thank you in advance.
This is what I'd do (after a little more polish):
public static bool PromptForInt(string promptString, out int result, string helpString = null)
{
while (true)
{
Console.WriteLine(promptString);
var response = Console.ReadLine();
if (string.Equals(response, "Q", StringComparison.OrdinalIgnoreCase))
{
result = 0;
return false;
}
if (helpString != null && string.Equals(response, "H", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine(helpString);
continue; //skip back to the top of the loop
}
if (int.TryParse(response, out result))
{
return true;
}
}
}
You could right similar functions for other types (for example, double or DateTime, always using typeName.TryParse.
In terms of polishing, you might want to have a useful error message if the user doesn't enter "Q", "H" or a valid int. Otherwise...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am wondering can someone please tell me where I am going wrong with this FizzBuzz.
I get an error "not all code returns a value and struggling to find out exactly how to fix it.
My code is below:
for (int i = 0; i < input; i++)
{
if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else
{
Console.WriteLine(i);
}
}
And the test case is this:
[Test]
public void Test1()
{
var solution = new Solution();
Assert.AreEqual(solution.PrintFizzBuzz(15), "FizzBuzz");
}
First of like other people have said, not all the code is present so it's difficult for us to help. But I'll try anyway.
When testing with Assert.AreEqual the function PrintFizzBuzz should return something, in this case the string "FizzBuzz". But if you are using the Console.WriteLine method it will return nothing. The Console.Writeline method will print the string to the console, but the console is not actually the 'program', it's just for visualising some things like logging or debugging.
So to fix your issue you should use return instead of Console.Writeline and let your method PrintFizzBuzz return a string instead of voiding and printing it to the console. It's probably also better to rename your method in this case, because it doesn't print FizzBuzz anymore.
Your code has also another issue and that's when you input 15 it will print out "Fizz", because the check you do is modulo 3 and 15 % 3 = 0. You should order your check the otherway around, from specific to less specific.
An example for returning a string would be:
string SomeMethod()
{
return "Some String"
}
not all code returns a value
Means your method declared having a return type and not void but you are not returning anything from your method. One example case:
int Add(int a, int b)
{
int c = a + b;
// no return specified would through the same error
}
This question already has answers here:
C# How to loop user input until the datatype of the input is correct?
(4 answers)
Closed 6 years ago.
I trying to solve this code so it repeats exception until input is a number. right now it stop right first attempt and I do know how to place while loop.
int nomer2;
WriteLine("Write Number");
try
{
nomer2 = Convert.ToInt32(ReadLine());
WriteLine("here is my Number {0}", nomer2);
}
catch (Exception)
{
WriteLine("Error: Enter Number");
}
Its recommended not to use exceptions unless it is really unexpected what the result would be. You can use the TryParse function which tries to convert the string that is passed to it to an integer. If the conversion was successful, the integer is returned by reference in the second param and the function returns true, otherwise, it returns false.
int nomer2;
string input = string.Empty;
do
{
Console.WriteLine("Write Number");
input = Console.ReadLine();
}
while (!int.TryParse(input, out nomer2)) ;
Console.WriteLine("here is my Number {0}", nomer2);
while(!int.TryParse(ReadLine(), out nomer2))
{
WriteLine("Write Number");
}
WriteLine("here is my Number {0}", nomer2);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Console.WriteLine("Enter value for Monday : ");
milesMon = Console.ReadLine();
try
{
dblMon = double.Parse(milesMon);
}
catch
{
Console.WriteLine("You entered an invalid number - a default of 0 has been set");
dblMon = 0;
while (true) break;
Console.WriteLine("Enter value for Monday : ");
milesMon = Console.ReadLine();
In it's current state the code only prompts the user after they enter incorrect data the first time they do it, I would like to know how to make it so it happens every time.
-Thanks
You should use a do or while loop to keep repeating the prompt until a valid double is entered. You should also consider adding some form of exit keywords. Like if they enter "exit, quit, q" etc.. Have it terminate the app instead of loop back around. However being a console app, ctrl + c will close it regardless of what it's doing (it's the kill command) but not everyone knows that.
bool repeat = true;
var dblMilesMon = (double)0;
do
{
Console.WriteLine("Enter value for Monday : ");
var strMilesMon = Console.ReadLine();
if (!double.TryParse(strMilesMon, out dblMilesMon))
Console.WriteLine("You entered an invalid number - please enter a numeric value.")
else
repeat = false;
}while (repeat);
//do something with dblMilesMon
You can use TryParse() to convert the input string to double, it will return false if the conversion failed; based on that input you can prompt the user that whether the input is valid or not. and this will loop until the user enter Exit
string inputVal = "";
double inputDoubleVal;
while (inputVal == "Exit")
{
Console.WriteLine("Enter value for Monday : ");
inputVal = Console.ReadLine();
if (double.TryParse(inputVal, out inputDoubleVal))
{
//Process with your double value
}
else
{
Console.WriteLine("You entered an invalid number - a default of 0 has been set");
}
}
Basically you want to write a loop. While the input is invalid, prompt the user. So you should have a bool variable called valid to indicate whether the input is valid. And than a while loop like this:
while (!valid) {
//...
}
In the while loop, prompt the user. So the code looks like this:
bool valid = false;
int input = 0;
while (!valid) {
Console.WriteLine ("Prompt");
try
{
input = Convert.ToInt32 (Console.ReadLine ());
valid = true;
}
catch {}
}
Hope this helps!
You can use recursion to create your end-less loop without using a for or while.
Also, instead of a try-catch statement, better use a TryParse
Doc ref: https://msdn.microsoft.com/en-us/library/bb384043.aspx
public int readInput(){
int val = 0;
Console.WriteLine("Enter a valid int");
string enteredVal = Console.ReadLine();
bool result = int.TryParse(enteredVal, out val);
if(result)
return val;
Console.writeLine("Try again, only int values allowed");
return readInput();
}
int val = readInput();
This question already has answers here:
Cannot implicitly convert type string to int
(4 answers)
Closed 8 years ago.
I'm on my way to learn C# by following the basic training tutorial from Lynda and trying to make some changes on their examples.
I'm stuck on an error that I can't find a solution for on Google.
Cannot implicitly convert type 'string' to 'int' (CS0029)
Code:
namespace l2
{
class Program
{
public static void Main(string[] args)
{
int arg;
arg = Console.ReadLine();
int result1;
result1 = formula(arg);
Console.WriteLine("the result is {0}",result1);
Console.ReadKey();
}
static int formula (int theVal){
return (theVal * 2 + 15);
}
}
}
I really don't understand why I get that error. My function is getting an int, the arg that I want to get from console is also an int. Where is the string that the compiler is talking about? :)
Console.ReadLine() returns a string.
What you want is
arg = int.Parse(Console.ReadLine());
The correct solution in this case will be.
string input;
input= Console.ReadLine();
int numberArg;
while (!int.TryParse(input, out numberArg))
{
Console.WriteLine(#"Wrong parameter. Type again.");
input= Console.ReadLine();
}
var result1 = formula(numberArg);
Console.WriteLine("the result is {0}", result1);
Console.ReadKey();
You could also attempt some subtle validation, by using the int.TryParse. Which will attempt to convert the value to an integer, if it indeed fails it will use the original value:
int id = 1;
int.TryParse("Hello", out id);
Console.WriteLine(id)
Output: 1
int id = 1;
int.TryParse("40", out id);
Console.WriteLine(id)
Output: 40
Also note that Console.ReadLine() will return a type of string. So to correctly solve your issue, you would do:
int arguement = 0;
while(!int.TryParse(Console.ReadLine(), out arguement)
{
Console.WriteLine(#"Error, invalid integer.");
Console.ReadLine();
}
So until they enter a valid integer they'll be trapped in the loop.