I´m using an input inside a Loop (While). Also what i want to do is verify the input of the user, inside a method, and if its not a number then it should return back again to ask the input. The problem is that when i try that i have to restart the program. Can someone explain me how to control the code so i can go back in the code? Thanks so much!
Console.WriteLine("Efetue a jogada ->");
string escolha = Console.ReadLine();
int verificaçaoEscolha = escolhaVerificacao(escolha);
if(valido == 1){
Console.WriteLine("Try again");
//Method
public static int escolhaVerificacao(string a) {
int b;
int valido = 0;
try {
int.TryParse(a, out b);
}
catch (FormatException) {
valido = 1;
}
return valido;
}
Int32.TryParse doesn't rise exceptions. It returns true if the input has been converted to an integer
public static bool escolhaVerificacao(string a)
{
int b;
return int.TryParse(a, out b);
}
and call it with
Console.WriteLine("Efetue a jogada ->");
string escolha = Console.ReadLine();
bool verificaçaoEscolha = escolhaVerificacao(escolha);
if(!verificaçaoEscolha)
{
Console.WriteLine("Try again");
}
Related
I wrote a do-while loop but it does not run through while condition somehow.
When I type in invalid characters it should go back to beginning and repeat as it's supposed to.
I ran the code step by step on Visual Studio and it shows that code does not even go through while condition. (no matter what the input value is)
Can someone please help me?
Many thanks in advance!
using System;
using static System.Console;
namespace a5
{
class Program
{
const string acceptedLetters = "EHLNTXZ";
static void Main(string[] args)
{
GetUserString(acceptedLetters);
ReadKey();
}
static string GetUserString(string letters)
{
string invalidCharacters;
do
{
invalidCharacters = null;
Write("Enter : ");
string inputCharacters = ReadLine();
foreach(char c in inputCharacters)
{
if(letters.IndexOf(char.ToUpper(c))==-1)
{
invalidCharacters = c.ToString();
}
}
if(invalidCharacters != null)
{
WriteLine("Enter a valid input");
}
return inputCharacters;
} while (invalidCharacters != null);
}
}
}
The problem is that you return the inputed string at the end of the loop no matter the validation done.
You can use a boolean to check this validity.
Also you don't need to parse all the string and you can break the inner loop on the first invalid char.
I renamed the string as result to use a standard pattern and to be more clean.
For example:
static string GetUserString(string letters)
{
string result;
bool isValid;
do
{
Console.Write("Enter : ");
result = Console.ReadLine();
isValid = true;
foreach ( char c in result )
if ( letters.IndexOf(char.ToUpper(c)) == -1 )
{
isValid = false;
Console.WriteLine("Enter a valid input");
break;
}
}
while ( !isValid );
return result;
}
The line return inputCharacters; makes it leave the loop.
I think you meant:
} while (invalidCharacters != null);
return inputCharacters;
using System;
using static System.Console;
namespace a5
{
class Program
{
const string acceptedLetters = "EHLNTXZ";
static void Main(string[] args)
{
GetUserString(acceptedLetters);
ReadKey();
}
static string GetUserString(string letters)
{
string invalidCharacters;
do
{
invalidCharacters = null;
Write("Enter : ");
string inputCharacters = ReadLine();
foreach(char c in inputCharacters)
{
if(letters.IndexOf(char.ToUpper(c))== -1)
{
invalidCharacters = c.ToString();
}
}
if(invalidCharacters != null)
{
WriteLine("Enter a valid input");
}
} while (invalidCharacters != null);
return inputCharacters;
}
}
}
I have public string method with an if/else statement. When I don't put a return keyword on the else, I get the error that not all code paths return a value but when I add the return to the else statement, I get an Use of unassigned local variable 'result'. When I do return "Please enter a valid number";, nothing displays on the console when I type in any letter. I need to let the user know that they entered something in that couldn't be converted into an integer.
public string AddNumbers(string userInputString)
{
int result;
int num2 = RandomNumberInt();
bool isTrue = int.TryParse(userInputString, out int num1);
if (isTrue == true)
{
result = num1 + num2;
Console.WriteLine("Adding your number and a random number, please wait...");
Thread.Sleep(1000);
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
isTrue = true;
return result.ToString();
}
else
{
return "Please enter a valid number";
}
}
It's because your method is asking for a return. But since you have an if, let's put it this way
Team Leader: Hey bob I want you to finish this job.
In here you are expecting that bob will finish your job but you put a condition
You: If I can go to office today sir.
since you have an If condition, what if you can't go today? Does it mean you can't finish the job tomorrow and any other day? That's why it says not all code paths return a value because you never gave other/default value
Going back in your code, you ask
if (isTrue == true)
{
result = num1 + num2;
Console.WriteLine("Adding your number and a random number, please wait...");
Thread.Sleep(1000);
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
isTrue = true;
return result.ToString();
}
but what if it is not true, then it will go to else. You can set int result = 0 so it is defined from start when else run and it will not return an error of unassigned local variable.
public string myMethod()
{
int result = 0; //This must have a default value so in else part it is not unassigned when you return.
int num2 = RandomNumberInt();
bool isTrue = int.TryParse(userInputString, out int num1);
if(isTrue)
{
//do something in result here
return result.toString(); //This will return your in value as string
}
else
{
return "Your message as string" // This will return any string to provide for string return of the method
}
}
Your problem regarding not displaying the string "Please enter a valid number" is a different issue. You have to post also what method calls the AddNumbers method that will use the returned string. For use the problem is in that method because your if and else is in correct format;
Whenever you get confused by application logic, it is often helpful to break the logic down into pieces. This gives you an opportunity to think through the problem and decide how the tasks add up to give you the final result.
Start at a high level and sketch out the overall flow:
static public void MethodNameThatDescribesThisActivity()
{
var userResponse = ReadIntegerFromConsole("Please enter an integer.");
var randomNumber = RandomNumberInt();
DisplaySum(userResponse, randomNumber, 1000);
}
Then implement the pieces:
static public int ReadIntegerFromConsole(string prompt)
{
int result;
while (true)
{
Console.WriteLine(prompt);
var input = Console.ReadLine();
var ok = int.TryParse(input, out result);
if (ok) break;
Console.WriteLine("That isn't a valid integer.");
}
return result;
}
static public void DisplaySum(int userNumber, int randomNumber, int delay)
{
var sum = userNumber + randomNumber;
Thread.Sleep(delay);
Console.WriteLine("The total of {0} + {1} = {2}", userNumber, randomNumber, sum);
}
If you do it this way, it often solves the logic problem for you. And it also makes your code easier to read.
I am trying to use TryParse method in c#.
I am creating a program which takes input from user and if it is integer then return to a variable. Program works fine when input is valid integer but once I enter the invalid number like 12sd it returns a=0. Where is the mistake.
public int checkValidNumber()
{
Program obj = new Program();
int a = 0;
string str = Console.ReadLine();
if(!int.TryParse(str, out a))
{
Console.WriteLine("Please enter a valid number");
obj.checkValidNumber();
}
return a;
}
Calling in Main using
Program obj = new Program();
int a = obj.checkValidNumber();
where as Program is a Class, Consider a console application please
You should replace obj.checkValidNumber(); with:
a = obj.checkValidNumber();
//Or
return obj.checkValidNumber();
In addition checkValidNumber is a member function of Program, there is no reason to create a new instance of Program in each call
public int checkValidNumber()
{
int a=0;
if(!int.TryParse(Console.ReadLine(), out a))
{
Console.WriteLine("Please enter a valid number");
return checkValidNumber();
}
return a;
}
But probably better to use a while loop for this, rather than a recursive call:
public int checkValidNumber()
{
int a=0;
while(!int.TryParse(Console.ReadLine(), out a))
{
Console.WriteLine("Please enter a valid number");
}
return a;
}
If using C#7.0 see the new usage of an out variable for the TryParse
Hello im wondering how to return to previous statement in C#
For example i want to show user readline again when he filled it wrong and when he will do it right it will show him the next line of code/statement(in this exam. Console.WriteLine("Hi"))
How could i do it?
int num;
string prvnicislo;
prvnicislo = Console.ReadLine();
while (true)
{
if (int.TryParse(prvnicislo, out num))
{
Convert.ToInt32(prvnicislo);
}
else
{
Console.WriteLine("'{0}' is not int, try it again:", prvnicislo);
prvnicislo = Console.ReadLine();
}
}
Console.WriteLine("Hi");
I think this will work:
int num;
string prvnicislo = Console.ReadLine();
while (!int.TryParse(prvnicislo, out num))
{
Console.WriteLine("'{0}' is not int, try it again:", prvnicislo);
prvnicislo = Console.ReadLine();
}
Console.WriteLine("Hi");
Notice that there is not necessary to use Convert.ToInt32 because if the parsing has been succeed the TryParse method will assign the parsed int value to num.
check the following code snippet
int num;
string prvnicislo;
prvnicislo = Console.ReadLine();
while (true)
{
if (int.TryParse(prvnicislo, out num))
{
Convert.ToInt32(prvnicislo);
break;
}
else
{
Console.WriteLine("'{0}' is not int, try it again:", prvnicislo);
prvnicislo = Console.ReadLine();
}
}
Console.WriteLine("Hi");
Hope this helps
if this can be of any help
string prvnicislo = String.Empty;
bool isEntryWrong = true;
do
{
Console.Write("Enter data: ");
prvnicislo = Console.ReadLine();
int num;
if(int.TryParse(prvnicislo, out num))
{
isEntryWrong = false;
}
else
{
Console.WriteLine("'{0}' is not int, try it again:", prvnicislo);
}
} while (isEntryWrong);
Console.WriteLine("Hi")
So I recently started my first coding course for C#. I am currently trying to write a short program that prints out Yay! as many times as I indicate. Now to prevent any format exceptions, I've tried to add a try and catch to it. But, for some reason this isn't working and I can't seem to figure out why. The code is below:
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
var number = int.Parse (entry);
bool print = true;
while(print)
{
try
{
if(number <= 0)
{
print = false;
}
else
{
Console.WriteLine("Yay!");
number -= 1;
}
}
catch(FormatException)
{
Console.WriteLine("You must enter a whole number.");
}
}
Now to my knowledge, I have everything I need to make this work. Can anyone see where I went wrong with this?
Thanks a lot for reading!
It's
var number = int.Parse (entry);
that should throw the exception, and since it's beyond try {} scope, the
exception has not been caught. Move the fragment into the scope:
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
bool print = true;
try {
// int.Parse is within the try {} scope now
var number = int.Parse (entry);
while(print) {
...
}
}
catch(FormatException) {
Console.WriteLine("You must enter a whole number.");
}
Or convert int.Parse into int.TryParse and drop try {...} catch {...} at all (a better solution)
Console.Write("Enter the number of times to print \"Yay!\": ");
int number;
if (!int.TryParse(Console.ReadLine(), out number)) {
Console.WriteLine("You must enter a whole number.");
return;
}
bool print = true;
// There's no need in try {} catch {} now
while(print) {
...
}
You need to place your int.Parse inside your try-catch block.
Here's a revised version of your code.
static void Main(string[] args)
{
bool print = true;
while (print)
{
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
try
{
var number = int.Parse(entry);
for (int i = 0; i < number; i++)
{
Console.WriteLine("Yay!");
}
}
catch (FormatException)
{
Console.WriteLine("You must enter a whole number.");
}
}
}