Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I prevent crashing due to invalid input in C#?
    primarykey
    data
    text
    <p>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.</p> <p>What I want to do is:</p> <ol> <li><p>Prevent the program from crashing from invalid input.</p></li> <li><p>Display an error message if the input is invalid</p></li> <li><p>Have the program continue where it left off, without affecting the rest of the program.</p></li> </ol> <p>Also, a part of my program involves division. Is there a way to prevent the user from entering all zeros?</p> <p>This is in C#</p> <p>My code:</p> <pre><code>using System; </code></pre> <p>using System.Collections.Generic; using System.Linq; using System.Text;</p> <p>namespace OverallCalculator {</p> <pre><code>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); } } </code></pre> <p>} </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload