C# stop user inputting a character/string instead of integer [duplicate] - c#

This question already has answers here:
How can I validate console input as integers?
(10 answers)
Closed 6 years ago.
I am asking users to input a int for their age but the program crashes when they input a string(obviously).
How would I go about allowing them to input a char/string but the program to display a funny message and then quit?.
This is what I have got so far:
Console.WriteLine("Please can you enter your age");
int userage = Convert.ToInt32(Console.ReadLine());
if (userage < 16)
{
var underage = new underage();
underage.text();
}
else if (userage>122)
{
Console.WriteLine("No one has ever reached this age and so you can't possibly be this old");
Console.WriteLine("Please enter a different age next time!");
Console.WriteLine("Unless you really are this old, in which case don't work!!");
Console.WriteLine("Press any key to exit the program.\n");
Environment.Exit(0);
}
else if(userage<122)
{
Console.WriteLine("Ah brilliant, you are old enough to use our services\n");
Console.WriteLine("We shall continue as first planned\n");
}
else
{
}

try:
Console.WriteLine("Please can you enter your age");
int userage;
if (int.TryParse(Console.ReadLine(), out userage))
{
//your if block
}
else
{
Console.WriteLine("Your input is funny and I am a funny message\n");
Environment.Exit(0);
}

Related

How to multiply correctly two numbers in a method?

{
Console.ForegroundColor= ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.Clear();
Console.WriteLine("Please enter your name and I will tell you how many letters your name has!");
string name = Console.ReadLine();
Count(name);
Console.WriteLine("Now tell me two numbers and I will multiply them!");
Console.Read();
try
{
Multiply();
}
catch (FormatException)
{
Console.WriteLine("You must enter a number!");
}
}
public static void Count(string name)
{
Console.WriteLine("Your name has {0} letters!", name.Length);
}
public static void Multiply()
{
string firstNum = Console.ReadLine();
string secondNum = Console.ReadLine();
int num = Int32.Parse(firstNum);
int num1 = Int32.Parse(secondNum);
int result = num * num1;
Console.WriteLine("The result is {0}", result);
}
Im a beginner and Im learning about methods so I made this simple code where the user should enter two numbers and I should multiply them, the problem is, whenever I enter two random numbers, I am getting some completely different numbers back no matter if i want to add them, multiply them or something third.
I cannot figure out why the "num1 * num2;" is not giving me a correct number. E.G. 54*19 should give me 1026, but instead its giving me -15.
you need to comment on the Console.Read(); line. this is the main cause.
I have run your code by commenting on the above line and it works as expected for me
Also, you need to handle the scenarios when the user can enter a non-integer input, so you could use int.TryParse for the same.
Also, try to handle the scenario where the integer value is very large and the multiplication of two numbers exceeds the integer max value.

How to do while loop/Do while loop with sentinel value with switch

Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}

Console Keypress not working?

So I'm making a console-based text game to learn more C# but I'm now stuck and have resorted to SO.
This might be an obvious answer but I require another pair of eyes to help me. I've checked the other questions on here and they don't seem to aid me.
In my Main(), I have the following:
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
if (age < 18)
{
Console.WriteLine("I'm sorry, you'll now be transferred to a non-explicit version.");
Console.WriteLine("\n<Press any key to continue>");
Console.ReadKey();
Console.Write("\nPlease wait...");
for (int t = 5; t >= 0; t--)
{
Console.CursorLeft = 22;
Console.Write("{0:00}" + " seconds remaining", t);
Thread.Sleep(1000);
}
Console.WriteLine("");
Console.WriteLine("\nTo proceed, please press any key...");
Console.ReadLine();
NonExplicit();
}
Self explanatory. Once it hits the NonExplicit() method, the following is called:
char yes = Console.ReadKey().KeyChar;
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadKey().ToString();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
What seems to happen is that, when 'y' or 'Y' is pressed:
1) It requires enter to be hit to register the above.
2) It runs both the if & else WriteLines, which I assume is in conjunction with 1)?
How can I amend my code so that when 'y/Y' is pressed, it reads the correct criteria? Or how can I remove the need for Enter to be pressed to proceed?
Used your code below, I tested it and it works.
I moved the char yes = Console.ReadKey() to below the Console.WriteLine().
I changed the name = Console.ReadKey() to Console.ReadLine() because a name is more then 1 key.
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
char yes = Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadLine();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
Console.ReadKey(); // I put this here so the program wouldn't exit
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
In your code, after Console.WriteLine("\nTo proceed, please press any key..."); you have Console.ReadLine(); which expects you to enter a line in the console (not reading till you press enter) and then in your second method, you're trying to read the console again (but this time for a single key).
Wouldn't it help if you remove the first Console.ReadLine() ?
And then you are trying to get the yes/no answer before asking your question (and before doing another ReadKey.
string result = Console.ReadLine();
if (result.ToUpper().Equals("Y"))
{
//any thing
}
char yes = Console.ReadKey(); // No need for .KeyChar
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
could be
int age = -1
Console.WriteLine("Before entering the unknown, could you please confirm your age? ");
while (age == -1)
{
if !(int.TryParse(Console.ReadLine(), out age))
{
Console.WriteLine("Please enter a valid age");
}
}
name = Console.ReadKey().ToString();
should be
name = Console.ReadLine();
if (yes == 'y' || yes == 'Y')
could be
if (yes.ToUpper() == "Y")

Not entering if/else block [closed]

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 8 years ago.
Improve this question
I have the following code. When I type 0 into the console, I expect the console to display "Please re-enter your age" but that if block is never entered and the program exits. What am I doing wrong?
Console.WriteLine("Please entre your first name:");
Console.ReadLine();
Console.WriteLine("Please enter your last name:");
Console.ReadLine();
Console.WriteLine("Please type your age:");
Console.ReadLine();
int minAge = 18;
int maxAge = 68;
if (minAge < 18)
if (maxAge > 68)
Console.WriteLine("Please re-enter your age");
else
Console.WriteLine("Please choose f for female or m for male:");
You are not reading the user input into an age variable. When you do, you need to take account of the user possibly typing non-numeric characters. You're also not wrapping your if/else blocks inside curly braces which is resulting in the logical flow not matching your intentions.
The following code reads the console input into an age variable, rejecting unparseable input by using int.TryParse, and it retains your minAge and maxAge values as constants. We keep looping until the user has input a valid number as an age, and exit if they are ineligible to continue because they are too young or too old:
const int minAge = 18;
const int maxAge = 68;
int age;
do
{
Console.WriteLine("Please type your age:");
} while (!int.TryParse(Console.ReadLine(), out age));
if (age < minAge || age > maxAge)
{
Console.WriteLine("I'm sorry, this application is for people aged {0} to {1} only", minAge, maxAge);
return; // or exit console app
}
Console.WriteLine("Please choose f for female or m for male:");
You're not storing inputted age. Because of that the program never reach the next part, since you're comparing minAge with minAge and maxAge with maxAge. Maybe you can use
int age = Convert.ToInt32(Console.Readline())
edit : if you don't want any exception, you can handle it by using
int age;
bool res = Int32.TryParse(Console.Readline(), out age);
if (!res)
Console.WriteLine("Please re-enter your age");
then use them in the next part
if (age < minAge || age > maxAge )
Console.WriteLine("Please re-enter your age");
else
Console.WriteLine("Please choose f for female or m for male:");
try the following may be it helps,
int userage;
Console.WriteLine("Please type your age:");
userage=int.Parse(Console.ReadLine());
int minAge = 18;
int maxAge = 68;
if (userage>minAge || userage<maxAge)
Console.WriteLine("Age is not accepted");
else
Console.WriteLine("Your Age is {0}",userage.ToString());
//do what ever you want
//Console.WriteLine("Please choose f for female or m for male:");
Console.ReadLine();

Finding min and max of user input data C# (without Linq) [duplicate]

This question already has answers here:
How to find the highest and the lowest number C#
(10 answers)
Closed 8 years ago.
I have a program that I am working on to practice for a midterm, it is a simple Gradebook program that allows the user to input as many grades from 0-100 as they want. I have various things that calculate at the end that work fine but I need the program to also display the lowest and the highest grades. I saw another post where someone talks about linq (?) I have not worked with this and haven't researched it yet. I figure if it isn't in the book I shouldn't need it yet. the code is long so I will try to only include what I think is necessary...
using System;
public class GradeBook
{
private int total;
private int gradeCounter;
private int aCount;
private int bCount;
private int cCount;
private int dCount;
private int fCount;
// automatic popert CourseName
public string CourseName { get; set; }
then in order to get the user input
public void InputGrades()
{
int grade; //grade made by user
string input; //text entered by user
Console.WriteLine("{0}\n{1}",
"enter integer in the range of 0-100.",
"Type <ctrl> Z and press endter to terminate input:");
input = Console.ReadLine(); //user input
//loop until user enters the end of file indicator
while (input != null)
{
grade = Convert.ToInt32(input);
total += grade; //create total to form sum
++gradeCounter;//increment the number of grades for average
// call method to increment appropriate counter
IncrementLetterGradeCounter(grade);
input = Console.ReadLine();
}//end while(input != null)
This is my first post to SO so if there is something I have done wrong please let me know. If more code is necessary let me know.
Add these two under int grade
int high = 0;
int low = 100;
And then in your while loop
if(input > high) high = input;
if(input < low) low = input;
And then after your while loop.
Console.WriteLine("The highest grade was: " + high);
Console.WriteLine("The lowest grade was: " + low);

Categories

Resources