Why value of a=0 after entering atleast one time invalid integer - c#

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

Related

How do I make the program request user input after inputting invalid data in C#?

I am not sure how to tackle this problem. I tried putting the do while loop in the method GetUserInput and then putting the for loop in the do while loop. It doesn't reset the question it just takes the number and adds it the numbers before it. Its a supposed to be a calculator program.
//This propgram will be used to make a calculator for the class project.
//The numbers are stored as floats as well as the result. Then displayed on console.
//V1 adds a do-while loop that repeats as long as the user wants.
//V2 adds a if and else logic for when the user input a character other than a number the program will close.
//V3 added a for-loop to increase the amount of numbers that can be considered in the calculation. It makes an array
//V4 added methods to get user input and sum the numbers
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Ulises Sanchez");
//Define 3 floating point numbers to capture the 2 inputs and the result
//floats are used to capture a broader range of numbers
float[] userInput = new float[10];
//stores the number of inputs the user requests
int numberOfUserInputs;
//define strings to store data read and also user prompts
string inputString;
string doMorefunctions = "Add More Numbers Together - y = yes - anything else for no";
//variable to test the condition to continue with calculations
bool moreActions;
do
{
Console.Clear();
numberOfUserInputs = GetuserInput(userInput);
//adds the numbers together
Summation(userInput, numberOfUserInputs);
//reset moreAction
moreActions = false;
Console.WriteLine(doMorefunctions);
inputString = Console.ReadLine();
if (inputString == "y" || inputString == "Y")
moreActions = true;
} while (moreActions);
}
//Gets the number of user inputs and stores each in the userInput array
static int GetuserInput(float[] inputArray)
{
int numberOfInputs;
string userInputPrompt = "How many numbers do you want to enter?";
//string continueMessage = "Hit any key to continue";
string errorMessage = "Invalid Input";
string inputString;
bool TryAgain;
Array.Clear(inputArray, 0, 10);
//Gets number of inputs from user
Console.Write(userInputPrompt);
inputString = Console.ReadLine();
numberOfInputs = int.Parse(inputString);
//Get inputs
for (int i = 0; i < numberOfInputs; i++)
{
Console.Write("Enter variable number {0}: ", i + 1);
inputString = Console.ReadLine();
if (Single.TryParse(inputString, out float result))
{
//if input is valid convert to float
inputArray[i] = float.Parse(inputString);
}
else
{
TryAgain = false;
Console.WriteLine(errorMessage);
inputString = Console.ReadLine();
if (inputString == "y" || inputString == "Y") TryAgain = true;
//if input is not valid input exit program
//Console.WriteLine(continueMessage);
//Console.ReadLine();
//System.Environment.Exit(1);
}
}
return numberOfInputs;
}
//takes the user input and performs a summation calculation
static void Summation(float[] inputArray, int numberOfInputs)
{
float summationResult = 0.0f;
for (int i = 0; i < numberOfInputs; i++)
{
summationResult += inputArray[i];
}
//display result to the screen
Console.WriteLine("Summation = {0}", summationResult);
}
}
We have this concept of "don't repeat yourself" (DRY) so we look for ways to make code that repeats itself not do so. Every one of your methods repeats the print/ReadLine process for asking a question
Let's have a method that asks the user for a string:
public string Ask(string q){
Console.WriteLine(q);
return Console.ReadLine();
}
Now we can say:
string name = Ask("what is your name? ");
Suppose blank input is invalid, let's use a loop to repeat the question:
public string Ask(string q){
string a = "";
while(string.IsNullOrEmpty(a)){
Console.WriteLine(q);
a = Console.ReadLine();
}
return a;
}
If the user gives no answer, they are stuck in the loop and the question is repeated until they give a valid answer
Now let's reuse this to ask for an int:
public int AskInt(string q){
return int.Parse(Ask(q));
}
Here we reuse Ask within AskInt so we don't do the print/read thing again and we leverage the "cannot renter blank" validation we already write
This however explodes if the user enters non ints
So let's use int.TryParse and keep looping while they enter garbage that doesn't parse;
public int AskInt(string q){
bool success = false;
into a=0;
while(!success){
success = int.TryParse(Ask(q), out a);
}
return a;
}
The user can only get to the last line if they enter an int
If you also want to add range validation, for example, you can put an int min, int max into your method parameters and inside the loop do success = success && a <= && a >= min
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);
The idea is to write one method that does one thing really well I.e. "ask the user for a string" and then reuse that when we write the next method that does one thing well, so we end up with two methods that do two things well. Giving the methods a sensible name allows us to package up that bit of logic they do into a few words and make out code read like a book. It doesn't need as many comments then
//ask the user what their next guess is
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);
This comment isn't needed; we can easily deduce the same just by reading the code.

How to check if a returned method in C# is an integer

I would like to loop a method as long as the method does not return an integer in C#.
public static int isAnInt()
{
rQuit = Console.ReadLine();
if (Int32.TryParse(rQuit, out isQuit) == false)
{
Console.WriteLine("Enter value again but as a number");
}
return isQuit;
}
// Whilst inside the main method /
while (int.TryParse(isAnInt() , out isQuit ) == false)
{
Console.WriteLine("This method is not an int try insert an int"); // For the method isAntInt I am trying to only
//loop the method as
// long as it is not an integer.
}
Console.WriteLine("Type something");
//It saves input
int thenumber;
//Check if Input is a number
while(!int.TryParse(Console.ReadLine(), out thenumber))
{//If input not a number then output this
Console.WriteLine("Not a number");
}
Here you go

Main Menu for a mastermind game

I am trying to create the menu for a mastermind game which can be ran in a command prompt using C#. The issue I am running into is capturing the users input for the menu. If they enter a 2 then it should display that they entered the number two and if not then it would say they have not displayed the number two.
The issue I am having is that it wont turn the users input into a working integer and will either come up saying that it can't explicitly convert from System.ConsoleKeyInfo to int or string to int.
using System;
namespace MasterMind
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" MasterMind's Main Menu");
Console.WriteLine(" 1: Play");
Console.WriteLine(" 2: Help");
Console.WriteLine(" 0: Exit");
int userinput = Console.ReadKey();
if (Nuserinput == 2);
{
Console.WriteLine("This is a number 2");
}
else
{
Console.WriteLine("This is not a number 2");
}
}
}
}
Console.ReadKey() returns a ConsoleKeyInfo object, which is not an int object. You can get a char from that, for example:
var key = Console.ReadKey();
var keyChar = key.KeyChar;
If you expect that char value to represent an integer, you can convert it to one:
int keyInt = (int)Char.GetNumericValue(keyChar);
Aside from other error checking you might want to put in place in case the user doesn't enter a valid integer, this would at least get your the integer value you're looking for.
Console.ReadKey() returns a ConsoleKeyInfo, so you'll need to do something like this:
ConsoleKeyInfo data = Console.ReadKey();
int num;
if (int.TryParse(data.KeyChar.ToString(), out num) && num == 2)
{
Console.WriteLine("This is a number 2");
}else{
Console.WriteLine("This is not a number 2");
}
Change your
int userinput = Console.ReadKey();
if (Nuserinput == 2)
To:
string userInput = Console.ReadKey().KeyChar.ToString();
if(input == "2")
Or covert the string to an int as shown in other answers. But for this, a string works fine.

Noob c#. Trying to verify user input inside a method

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");
}

C# console application - commission calculator - how to pass variables into Main()

I can't figure out how to pass total, sale and comm into Main().
Anybody got an idea how to get those variables into Main and display (output) them there with the names?
Right now I can just output the variables in calcComm ...
Thanks in advance
Philip
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication38
{
class Program
{
public static void getsales()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
}
calcComm(total);
}
public static void calcComm(double total)
{
double comm = 0;
comm = total * 0.2;
Console.WriteLine(comm);
}
public static void Main ()
{
Console.WriteLine(" Sunshine Hot Tubs \n Sales Commissions Report\n");
char Letter;
const string name1 = "Andreas";
const string name2 = "Brittany";
const string name3 = "Eric";
string inputLetter;
string name;
Console.WriteLine("Please enter intial or type 'z' to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
while (Letter != 'z')
{
if (Letter == 'a')
{
name = name1;
getsales();
}
else if (Letter == 'b')
{
name = name2;
getsales();
}
else if (Letter == 'e')
{
name = name3;
getsales();
}
else
{
Console.WriteLine("Invalid entry try again");
}
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
}
}
}
}
This gives an array of strings corresponding to the command line parameters.
Main(string [] args)
By the way, when dealing with monetary units, it's better to use decimal than double.
You should be using objects, then you can make those public.
class Sales
{
public double total;
public double sale;
public double comm;
...
public void CalcComm()
{
...
}
}
Then you can reference them like this:
Sales.total, Sales.sale
Or you can make them global but that's not normally advisable.
Look into the return keyword in C#; get your functions to return the relevant data back to main and have it make use of it.
Consider this example for how to add command line arguments. If you need them to be programmatically added consider writing a wrapper program and starting the Process inside it.
using System;
class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null"); // Check for null array
}
else
{
Console.Write("args length is ");
Console.WriteLine(args.Length); // Write array length
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Console.Write("args index ");
Console.Write(i); // Write index
Console.Write(" is [");
Console.Write(argument); // Write string
Console.WriteLine("]");
}
}
Console.ReadLine();
}
}
either you can build up a Data Transfer Object that holds all these three variables instantiate it and then return it to your main function.
You could also make use of variables that are passed as references instead of by value and use the updated reference value. Read about pass by value type & reference type for c# and the ref keyword.

Categories

Resources