How do I prevent crashing due to invalid input in C#? - c#

The program I've written is set to only accept positive integers as input. If the user inputs a letter instead, then it crashes. Negative integers don't cause any problems, though it's not 'valid' in regards to how my program functions.
What I want to do is:
Prevent the program from crashing from invalid input.
Display an error message if the input is invalid
Have the program continue where it left off, without affecting the rest of the program.
Also, a part of my program involves division. Is there a way to prevent the user from entering all zeros?
This is in C#
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue;
do
{
Console.WriteLine("Enter Striking Level: ");
string striking = Console.ReadLine();
Console.WriteLine("Enter Grappling Level: ");
string grappling = Console.ReadLine();
Console.WriteLine("Enter Submission Level: ");
string submission = Console.ReadLine();
Console.WriteLine("Enter Durability Level: ");
string durability = Console.ReadLine();
Console.WriteLine("Enter Technical Level: ");
string technical = Console.ReadLine();
Console.WriteLine("Enter Speed Level: ");
string speed = Console.ReadLine();
Console.WriteLine("Enter Hardcore Level: ");
string hardcore = Console.ReadLine();
Console.WriteLine("Enter Charisma Level: ");
string charisma = Console.ReadLine();
int gra = Convert.ToInt32(grappling);
int str = Convert.ToInt32(striking);
int dur = Convert.ToInt32(durability);
int spd = Convert.ToInt32(speed);
int tec = Convert.ToInt32(technical);
int hdc = Convert.ToInt32(hardcore);
int cha = Convert.ToInt32(charisma);
int sub = Convert.ToInt32(submission);
int total = str + gra + sub + dur + tec + spd + cha + hdc;
int overall = total / 8 + 8;
Console.WriteLine("The Overall is " + overall);
Console.WriteLine("Do you wish to continue? y/n? ");
if (Console.ReadLine() == "y")
{
shouldContinue = true;
}
else break;
} while (shouldContinue == true);
}
}
}

int value = 0;
if (!int.TryParse(input, out value))
{
MessageBox.Show("Oops");
} else {
// use the value in the variable "value".
}

static void Main(string[] args)
{
bool validInput = false;
string inputString;
UInt32 validPositiveInteger = 0;
while (!validInput)
{
Console.WriteLine("Please enter a positive 32 bit integer:");
inputString = Console.ReadLine();
if (!UInt32.TryParse(inputString, out validPositiveInteger))
{
Console.WriteLine("Input was not a positive integer.");
}
else if (validPositiveInteger.Equals(0))
{
Console.WriteLine("You cannot enter zero.");
}
else
{
validInput = true;
//Or you could just break
//break;
}
}
Console.WriteLine(String.Format("Positive integer = {0}", validPositiveInteger));
}

Here you go:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue = true;
while (shouldContinue)
{
int strikingLevel = GetValue("Enter Striking Level: ");
int grapplingLevel = GetValue("Enter Grappling Level: ");
int submissionLevel = GetValue("Enter Submission Level: ");
int durabilityLevel = GetValue("Enter Durability Level: ");
int technicalLevel = GetValue("Enter Technical Level: ");
int speedLevel = GetValue("Enter Speed Level: ");
int hardcoreLevel = GetValue("Enter Hardcore Level: ");
int charismaLevel = GetValue("Enter Charisma Level: ");
int total = strikingLevel + grapplingLevel + durabilityLevel + submissionLevel +
technicalLevel + speedLevel + charismaLevel + hardcoreLevel;
int overall = total / 8 + 8;
Console.WriteLine("\nThe Overall is {0}.", overall);
while (true)
{
Console.WriteLine("Do you wish to continue? y/n? ");
string response = Console.ReadLine();
if (response.Equals("y", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = true;
break;
}
else if (response.Equals("n", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("no", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = false;
break;
}
}
}
}
private static int GetValue(string prompt)
{
while (true)
{
Console.WriteLine(prompt);
string input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if (value <= 0)
Console.WriteLine("Please enter a positive number.");
else
return value;
}
else
{
Console.WriteLine("Please enter a number.");
}
}
}
}
}

Yes... before you do anything calculations, you need to validate the data you are going to use. If any data is incorrect, then you display a messagebox detailing the errors and return focus to the form so the user can fix the errors. Repeat as necessary.

I wrote this one many moons ago when I first learned C#. It is a conversion from a VB function that I got back in VB5 days. The major benefit of the function is that there is no error - an input will just not allow any characters outside of the predefined list.
/***********************************************************************
* bool ValiText(char inChar,
* string valid,
* bool editable,
* bool casesensitive
* Description: Validate Input Characters As They Are Input
* Notes: For each control whose input you wish to validate, just put
* e.Handled = ValiText(e.KeyChar, "0123456789/-" [,true][,true])
* In The KeyPress Event
***********************************************************************/
public bool ValiText(char inChar, string valid, bool editable, bool casesensitive)
{
string inVal = inChar.ToString();
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
/// Case InSensitive - Make Them Both The Same Case
if (!casesensitive)
{
tst = tst.ToLower();
inVal = inVal.ToLower();
}
return tst.IndexOf(inVal,0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid, bool editable)
{
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
return tst.IndexOf(inChar.ToString(),0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid)
{
return valid.IndexOf(inChar.ToString(),0,valid.Length) < 0;
}
Note That This Will Not Work On A Web APP.

Related

C# re-enter value after wrong input instead of restarting the program

so I am trying to make a multiplication table with c#, and I want that when user give a wrong input in code it should not start the program from start but just ask to re-enter that value. when I run this code and put wrong input. it will ask to display the multiplication table again. but I want that if I give wrong input at "start value" then it will only ask for re-entering the start value but not the whole input
public void Multi()
{
Console.Write("\n\n");
bool tryAgain = true;
while (tryAgain)
{
try
{
Console.Write("Display the multiplication table:\n ");
int t = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("\n");
Console.WriteLine(" Start value ");
Console.WriteLine("\n");
Console.WriteLine(" End value \n");
int end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
SwapNum(ref start, ref end);
Console.Write("\n");
Console.WriteLine("Display the table\n");
int i = start;
do
{
Console.WriteLine(t + " * " + i + " = " + t * i);
//Console.WriteLine("{0} * {1} = {2}", t, i, t*i);
i++;
} while (i <= end);
}
catch (Exception ex)
{
Console.WriteLine("Please Enter the inter number ");
}
}
}
static void SwapNum(ref int x, ref int y)
{
if (x >= y)
{
int temp = x;
x = y;
y = temp;
}
}
Change Parse into TryParse; let's extract a method for this
private static int ReadInt(string prompt) {
while (true) {
Console.WriteLine(prompt);
int result;
if (int.TryParse(Console.ReadLine(), out result))
return result;
Console.WriteLine("Sorry, it's not a correct integer value, please try again.");
}
}
...
public void Multi() {
Console.Write("Display the multiplication table:\n ");
// Now we keep asking user until the correct value entered
int t = ReadInt("Start value");
...
}

Return to Start/Top in C # console application

I am trying to go back to start in c# console program, and i am somehow able to do it, but the problem is that i am not able to do it using the Y/N statement. mean if i type the Y (yes) from keyboard then the program start from it's starting (beginning) point if i type N then it will terminate the program.
My Console code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace simple_calculation
{
class Program
{
static void Main(string[] args)
{
bool bktop = true;
string option;
while (bktop)
{
Console.WriteLine("Please enter the values");
int val = int.Parse(Console.ReadLine());
int val1 = int.Parse(Console.ReadLine());
int res = val + val1;
int red = val / val1;
Console.WriteLine("Please enter the operator");
string oper=Console.ReadLine();
if (oper == "+")
{
Console.WriteLine("sum is:" + res);
}
else if (oper == "/")
{
Console.WriteLine("division is:" + red);
}
else
{
Console.WriteLine("do you want to continue? enter Y/N");
option = Console.ReadLine();
if(option=="Y")
{
bktop = false;
}
else
{
bktop = true;
}
}
Console.ReadLine();
}
}
}
}
What I want: i want that when the program reaches to the else condition then there is a text appear in the console "do you want to continue? enter Y/N" if the user enter Y then the program start again and if the user enter N then the program will terminate.
Any help will be appreciated.
class Program
{
static void Main(string[] args)
{
// Change 1
bool bktop = true;
string option;
while (bktop)
{
bktop = true;
Console.WriteLine("Please enter the values");
int val = int.Parse(Console.ReadLine());
int val1 = int.Parse(Console.ReadLine());
int res = val + val1;
int red = val / val1;
Console.WriteLine("Please enter the operator");
string oper = Console.ReadLine();
if (oper == "+")
{
Console.WriteLine("sum is:" + res);
}
else if (oper == "/")
{
Console.WriteLine("division is:" + red);
}
else
{
Console.WriteLine("do you want to continue? enter Y/N");
option = Console.ReadLine();
// Change 2
if (option.ToUpper() != "Y")
{
bktop = false;
}
}
}
}
}

How to add user input together

My program has to add the previous number entered to the next one. This is what I have so far, and I got stuck. It adds up the number that I have entered, but I don't understand how I have to validate one number from previous.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
inputInt += inputInt;
Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);
} while (inputInt != QUIT);
}
Since there may be an indefinite number of entries, I don't know how to properly use an array.
If you are trying to find sum of numbers take another variable.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0,tempint=0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out tempint);
if (inputBool == true)
{
inputInt += tempint;
}
Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);
} while (tempint!= QUIT);
}
If you want the simplest solution, you can just keep track of the past 3 numbers and sum them up when you print
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int i1 = 0;
int i2 = 0;
int i3 = 0;
int inputInt = 0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
{
i3 = i2;
i2 = i1;
i1 = inputInt;
}
Console.WriteLine("Sum of the past three numbers is: {0}", i1+i2+i3);
} while (inputInt != QUIT);
}
This answer uses LINQ and Queues to do what you want.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0;
Queue myQ = new Queue();
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
{
if (myQ.Count() == 3)
{
myQ.Dequeue();
myQ.Enqueue(inputInt);
}
else
{
myQ.Enqueue(inputInt);
}
}
if (myQ.Count() == 3)
{
Console.WriteLine("Sum of the past three numbers is: {0}", myQ.Sum());
}
} while (inputInt != QUIT);
}
Use a list to store all of the numbers as they come in. Then at the end count how many items are in the list, and Sum() the entire list
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
List<int> allNumbers = new List<int>();
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
allNumbers.Add(inputInt); // Add a new element to the list
Console.WriteLine("Sum of the past " + allNumbers.Count + " numbers is: {0}", allNumbers.Sum());
} while (inputInt != QUIT);
}
you need to create a local variable to hold the output from int.TryParse. Also you do not need a do while loop, you can exit immediately when the input is -1. With these changes, keeping up with the last 3 numbers becomes much easier:
static void Main(string[] args)
{
const int QUIT = -1;
int[] last3 = new int[3];
// infinite loop, exit is done when input is -1
for(;;) {
Console.Write("Type a number (type -1 to quit): ");
var input = Console.ReadLine();
int tmp; // holds the int value of the input
if (int.TryParse(input, out tmp))
{
if (tmp == QUIT)
break; // input is -1
// input was an int, so lets move the last two towards
// the front of the array, last3[0] contained the oldest value
// which is gone now
last3[0] = last3[1];
last3[1] = last3[2];
// now overwrite the last item in the array with the newest value
last3[2] = tmp;
}
// add up the values, note if input was not a valid int, this will sum
// the last 3 valid values because the above if statement will only execute
// and change the values in the array if the user input was a number
var sum = last3[0] + last3[1] + last3[2];
Console.WriteLine("Sum of the past three numbers is: {0}", sum);
}
}

C# console application - commission calculator - how to use method within method

I'm new to C# and I have encountered some problems with my console application that I'm recently working on. I am trying to have 3 methods:
getsales to get the sales the user made, calcCom to calculate the commission for the sales and finally main to make them work and establish the program.
I'm having trouble to make those methods work with(in) each other.
After i entered all the sales, the program goes to the else-statement and tells me "invalid entry". Since i haven't really gotten to output the variables I didn't expect any kind of output, but I want the program to tell the user the commission and sale for each person.
Please excuse me if I misused any terms or words, like I said I am new to this language! :D
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;
Console.WriteLine();
}
}
public static void calcComm ()
{
double total = 0;
double comm = 0;
comm = total * 0.2;
}
static void Main()
{
Console.WriteLine(" Sunshine Hot Tubs \n Sales Commissions Report\n");
char Letter;
string name;
const string name1 = "Andreas";
const string name2 = "Brittany";
const string name3 = "Eric";
string inputLetter;
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();
calcComm();
}
if (Letter == 'b')
{
name = name2;
getsales();
calcComm();
}
if (Letter == 'e')
{
name = name3;
getsales();
calcComm();
}
else
{
Console.WriteLine("Invalid entry try again");
inputLetter = Console.ReadLine();
}
}
}
}
}
I think your problem is you need this:
if (Letter == 'a')
{
name = name1;
getsales();
calcComm();
}
else if (Letter == 'b')
{
name = name2;
getsales();
calcComm();
}
else if (Letter == 'e')
{
name = name3;
getsales();
calcComm();
}
else
{
Console.WriteLine("Invalid entry try again");
inputLetter = Console.ReadLine();
}
You also need to copy this code after the else block, at the very end of your while loop.
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
Also, remove this line from inside the else block. It isn't needed.
inputLetter = Console.ReadLine();
You probably intended to display the commision on the console. Change your getsales and calcComm to look like this:
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;
Console.WriteLine();
}
calcComm(total);
}
public static void calcComm (double total)
{
double comm = 0;
comm = total * 0.2;
Console.WriteLine(comm);
}
Then remove all calls to calcComm from the Main method.
The variable "total" is in the two methods and they do not persist the data that you are looking for between the two methods that you have defined. That is, the total variable in getSales() method is different from calcComm() method.
You should move this:
double total = 0;
outside of the two methods and put it within the class with a static scope. Like:
class Program
{
static double total;
Also, reinitialize total to zero within your getSales() method.
calcComm() doesn't do anything...
I think you might want to have some of your variables as global so that if they are modified by a method you can still retrieve their value, or even better pass them to the method and get them returned with the new values.
To declare global variables you should declare them inside the class Program but outside any method and then make sure that no other methods have variables with the same name

C# problems with a for loop

Can someone tell me why this doesnt work. When I enter the loop it prints everything instead of one line and get the users input. It prints Enter the integer the account numberEnter the integer the account balanceEnter the account holder lastname
Got it working thanks everyone, but now the searchaccounts doesnt work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class accounts
{
private int[] accountnum = new int[5]; //private accountnum array of five integer account numbers
private int[] accountbal = new int[5];//private balance array of five balance amounts
private string[] accountname = new string[5];//private accntname array to hold five last names
public void fillAccounts()
{
int bal;
int accountnumber;
string name;
for (int x = 0; x < 5; ++x)
{
Console.Write("Enter the integer the account number");
accountnumber = Console.Read();
Console.Write("Enter the integer the account balance");
bal = Console.Read();
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
accountnum[x] = accountnumber;
accountbal[x] = bal;
accountname[x] = name;
}
}
public void searchAccounts()
{
Console.WriteLine("Enter the account number");
int acctnum = Console.Read();
for (int x = 0; x < 6; ++x)
{
if (x < 5)
{
if (accountnum[x] == acctnum)
{
Console.WriteLine("Account #{0} has a balance of {1} for customer {2}", acctnum, accountbal[x].ToString("C"), accountname[x]);
break;
}
}
else
{
Console.WriteLine("You entered invalid account number");
}
}
}
public void averageAccounts()
{
int sum = 0;
int avg;
for (int x = 0; x < 5; ++x)
{
sum = accountbal[x] + sum;
}
avg = sum / 5;
Console.WriteLine("The average dollar amount is {0}", avg.ToString("c"));
}
}
class assignment3_alt
{
static void Main(string[] args)
{
accounts myclass = new accounts();
string userin;
myclass.fillAccounts();
int i = 0;
while (i != 1)
{//use the following menu:
Console.WriteLine("*****************************************");
Console.WriteLine("enter an a or A to search account numbers");
Console.WriteLine("enter a b or B to average the accounts");
Console.WriteLine("enter an x or X to exit program");
Console.WriteLine("*****************************************");
Console.Write("Enter option-->");
userin = Console.ReadLine();
if (userin == "a" || userin == "A")
{
myclass.searchAccounts();
}
else if (userin == "b" || userin == "B")
{
myclass.averageAccounts();
}
else if (userin == "x" || userin == "X")
{
break;
}
else
{
Console.WriteLine("You entered an invalid option");
}
}
}
}
}
Console.Read only reads a single character. You need to use Console.ReadLine.
Console.Write("Enter the integer the account number");
accountnumber = int.Parse(Console.ReadLine());
Console.Write("Enter the integer the account balance");
bal = int.Parse(Console.ReadLine());
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
You might also want to consider using int.TryParse instead of int.Parse so that you can better handle invalid input.
For your new question it is the same error. Just replace:
int acctnum = Console.Read();
with
int acctnum = int.Parse(Console.ReadLine());
or (preferably)
int acctnum;
if (!int.TryParse(Console.ReadLine(), out acctnum))
{
Console.WriteLine("You need to enter a number");
return;
}
The first will fail if the user doesn't enter a valid integer the second will print out a nice error message and return to the loop.
This is not an answer, as other have already put up some good ones. These are just a few tips about your code.
Instead of looping with while (i != 1), never changing the value of i and terminating the loop with break, it would be better to use a do-while loop, like this:
do
{
// blah blah
} while(userin != "x" || userin != "X")
It is less confusing than having a variable with no use at all.

Categories