C# Prohibiting user typing Words instead of numbers - c#

Having some problems with my Console Calculator
I want to prohibit user inputing a words instead of numbers.
I wrote this code and its converting words to zero but i want user to type a number instead of words. And if user still typing words program should ask user to type number.
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("----------------------");
Console.WriteLine("------Calculator------");
Console.WriteLine("----------------------");
do
{
double num1 = 0;
double num2 = 0;
double result = 0;
bool result0;
Console.WriteLine("Enter number one: ");
try
{
double.TryParse(Console.ReadLine(), out num1);
if ()
{
Console.WriteLine("Incorrect number!\nType another number:");
num1 = Convert.ToDouble(Console.ReadLine());
}
}
catch (Exception e)
{
}
Console.WriteLine("Enter number two: ");
num2 = Convert.ToDouble(Console.ReadLine());

You have to use double.TryParse() inside a if condition with negation operator.
If you want to force user to show "Incorrect number!\nType another number:" message till the user enters correct integer, use while() loop instead of if() condition.
while (!double.TryParse(Console.ReadLine(), out num1))
Console.WriteLine("Incorrect number!\nType another number:");
Why we should use double.TryParse() inside if condition?
double.TryParse(), parse string value to double and return true if conversion succeeded or not.
In your case, if user enters word instead of number then conversion will fail and use of !(negation) will iterate the loop again.

Related

How do I correctly convert strings to ints and input them into a list?

I'm making a program that asks the user for numbers for as long as he inputs positive values.
Here's the code that I currently have written, but I've not come to complete understanding with the function of and .Parse methods.
using System;
using System.Collections.Generic;
namespace Chapter
{
class Program
{
static void Main()
{
int input;
List<int> numbers = new List<int>();
Console.WriteLine("Input number: ");
input = Convert.ToInt32(Console.ReadLine());
numbers.Add(input);
while (input >= 0)
{
Console.WriteLine("Input number: ");
input = Convert.ToInt32(Console.ReadLine());
int val = Int32.Parse(input);
numbers.Add(val);
}
Console.WriteLine("the numbers you have input are");
foreach (int number in numbers)
{
Console.Write(number + " ");
}
}
}
}
The best way to achieve this is to use the Int32.TryParse method. This allows you to validate the input and handle it accordingly as well as converting to an int.
See the below example:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int input;
List<int> numbers = new List<int>();
do
{
Console.WriteLine("Input number: ");
while (!Int32.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("The value entered was not a number, try again.");
Console.WriteLine("Input number: ");
}
if (input >= 0)
numbers.Add(input);
}
while (input >= 0);
Console.WriteLine("the numbers you have input are");
foreach (int number in numbers)
{
Console.Write(number + " ");
}
}
}
Calling Convert.ToInt32(string) or Int32.Parse(string) do nearly the same thing. The difference is that Convert.ToInt32 will return 0 if the input is null and Int32.Parse will throw an exception.
If you were to look at the implementation you will find that Convert.ToInt32 calls Int32.Parse.
Anothing thing to note is that the Convert class allows you to convert a much wider range of types to intergers. The Int32.Parse method only accepts strings.
The issue with your code is in this block:
input = Convert.ToInt32(Console.ReadLine());
int val = Int32.Parse(input);
The input value has already been converted and is now an integer. This cannot be parsed (and doesn't have to be).
When working with user input, I'd rather use int.TryParse (what if user provides "bla-bla-bla"?).
I aslo suggest using infinite loop: keep asking user until (s)he puts negative value (in which case
we break the loop):
List<int> numbers = new List<int>();
// keep reading user input
while (true) {
Console.WriteLine("Input number: ");
// We try parsing (i.e. converting) user input - Console.ReadLine()
// into integer value - number
if (!int.TryParse(Console.ReadLine(), out int number))
// if parsing fails, say, user put "aha!", we let user know it
Console.WriteLine("Not a valid integer number, please, try again");
else if (number < 0)
// if number is negative stop asking user
break;
else
// non-negative numbers are added into the list
numbers.Add(number);
}
Console.WriteLine("the numbers you have input are");
// You can print the list in one go:
Console.Write(string.Join(" ", numbers));
Parseing detail:
int.TryParse(Console.ReadLine(), out int number)
int.TryParse takes user input Console.ReadLine() as an argument and returns true or false whether parsing succeeds or not. In case parsing succeeds, number contains parsed value.

How do you use a "char" as a sentinel value in a while loop

My Instructions:
Implement a C# console application/program that makes use of a sentinel controlled while-loop structure to continuously prompt, read and store the test results entered by the user. The user will stop his/her input sequence by entering a ‘x’ character. You also need to make use of a switch selection structure (nested inside of the while loop).
e.g code to be used:
char stop = 'x';
Console.WriteLine("Enter result (x to stop): ");
results = Convert.ToChar(Console.ReadLine());
while(results != stop)
{
Console.WriteLine("Enter result (x to stop): ");
results = Convert.ToChar(Console.ReadLine());
}
When I try to enter the 'x' as is, it does not work
you are using Console.WriteLine, but you should use Console.ReadKey and omit Convert.ToChar instead get the KeyChar property of the returned value.
so
while(results != stop)
{
Console.WriteLine("Enter result (x to stop): ");
results = Console.ReadKey().KeyChar;
}
should work, I didn't test it
You convert into wrong type: not every string can be converted into a single char (say, "xenogg").
However, every char can be represented as a string with a help of ToString():
char stop = 'x';
// Keep looping ...
while (true) {
// ...and asking user for input...
Console.WriteLine("Enter result (x to stop): ");
string results = Console.ReadLine();
// ... until (s)he puts "x"
// put StringComparison.OrdinalIgnoreCase if 'X' is exit as well as 'x'
if (string.Equals(results.Trim(), x.ToString(), StringComparison.Ordinal))
break;
// results is not "x"
//TODO: add relevant code here
}

C# code executes even when variable not assigned

As you can probably tell from my question, I am very new to coding. I am trying to make a calculator that computes some formulas that are used in physics. However, the code runs the formula before the user has time to enter a value for A, in this example at least. Here is the example:
case "f = ma":
Console.WriteLine("Type the value for M in KG:");
var FM = Console.Read();
Console.WriteLine("Type the value for A in M/S:");
var FA = Console.Read();
var FMARes = FM * FA;
Console.WriteLine("Your answer (in Newtowns) is " + FMARes);
break;
How am I able to check whether a value has been assigned to the variable A, and only run the formula after the variable has an assigned value? Thanks.
You need to use ReadLine instead of Read. You also need to do another ReadLine at the bottom so the user can see the result. And...you should validate that the user entered a valid number. This could be refactored a bit to avoid duplicate code - etc. - but see if this works for you! Good luck!!
static void Main(string[] args)
{
double fm;
double fa;
// Use ReadLine instead of Read
Console.WriteLine("Type the value for M in KG:");
var input = Console.ReadLine();
// Now you need to cast it to a double -
// -- but only if the user entered a valid number
if (!double.TryParse(input, out fm))
{
Console.WriteLine("Please enter a valid number for M");
Console.ReadLine();
return;
}
Console.WriteLine("Type the value for A in M/S:");
input = Console.ReadLine();
if (!double.TryParse(input, out fa))
{
Console.WriteLine("Please enter a valid number for A");
Console.ReadLine();
return;
}
// Now we have valid values for fa and fm
// It's a better programming practice to use the string format
// intead of + here...
Console.WriteLine($"Your answer (in Newtowns) is {fm * fa}");
// You need another read here or the program will just exit
Console.WriteLine("Press Enter to end the program");
Console.ReadLine();
}

Programme Qutting on user input of text instead of integer value

Just going through my code and I'm trying to solve an issue when testing for how can I get the programme to stop quitting the console when a user enters an option in the menu in text form for example they want to choose option "1" but decide to type the word "one" instead.
Thanks
Dan
int numNumbersReqd = 5;
int chosenOption = 0;
bool quit = false;
Console.WriteLine("*****************************************************************************");
Console.WriteLine("* This application is designed to allow you to select the number of numbers *");
Console.WriteLine("* you wish to enter, and sum the numbers that you provide. *");
Console.WriteLine("*****************************************************************************");
while (quit == false)
{
DisplayMenu();
chosenOption = ReadNumber("Please choose an option:");
quit = ProcessMenu(chosenOption, ref numNumbersReqd);
}
}
static void DisplayMenu()
{
Console.WriteLine("Select an option");
Console.WriteLine("1. Add numbers");
Console.WriteLine("2. Change amount of numbers to be entered");
Console.WriteLine("3. Quit");
}
static int ReadNumber(string prompt)
{
string text;
int number;
Console.Write(prompt);
text = Console.ReadLine();
number = int.Parse(text);
return number;
}
static bool ProcessMenu(int option, ref int numNumbers)
{
bool quit = false;
switch (option)
{
case 1:
int total;
total = GetTotal(numNumbers);
DisplayResult(total); // Programme was initally set to display the option that the user had entered from "displayMenu", by changing the variabel from option to total it will now display the answer of the numbers entrered by the user
break;
case 2:
numNumbers = ReadNumber("Please enter the number of numbers to be entered:");
break;
case 3:
quit = IsQuitting();
break;
default:
Console.WriteLine("Unknown option value entered");
break;
}
return quit;
}
static int GetTotal(int numbersReqd)
{
int total;
int index;
total = 0;
for (index = 0; index < numbersReqd - 1; index++)
{
total = total + ReadNumber("Please Enter Number:");
}
return total;
}
static void DisplayResult(int total)
{
Console.WriteLine("###############################################################################");
Console.WriteLine("###############################################################################");
Console.WriteLine("################## " + total.ToString() + " ##################");
Console.WriteLine("###############################################################################");
Console.WriteLine("###############################################################################");
}
static bool IsQuitting()
{
string response;
bool quit = false;
Console.Write("Do you really wish to quit?");
response = Console.ReadLine();
response = response.ToLower();
if (response == "yes") // Problem fixed with quit option, "YES" used before was specifying uppercase only inputs which are highly unlikely to be entered by the user which caused the programme to loop back to the start menu,
{
Console.WriteLine("Quiting");
quit = true;
}
return quit;
Use this:
int number;
while (!int.TryParse(Console.ReadLine(), out number)) // make sure that the user enters a valid number
Console.WriteLine("You did not enter a valid number");
// here number will have the value entered by the user.
TryParse will return true or false if the first parameter is a valid integer, and that value gets assigned to the second parameter using the out keyword.
"Regular" Parse will either convert the string to an integer, or throw an exception if it's not a valid integer.
Edit: cFrozenDeath suggested a good edit to my post, which encases the TryParse in a while loop. Effectively, what this is doing, is it will get input from the user UNTIL they enter a valid number. It is generally considered a good idea; if they enter in something incorrectly on accident, you most likely don't want to just immediately quit / end the program.
However, there is no logic in the while condition to also check if the value is "valid" from a requirements stand point. Your menu has 3 options, but if they enter 100 they've entered a mathematically valid integer but not a valid integer for your application. So you might want to also add a condition or two to check that number is within the acceptable range.
You can use use int32.TryParse() instead of int.Parse().
The value will be 0 when the parsing failed and you can then act accordingly.

How do I throw and exception using `if` and `else` if the user enter something that isn't a valid integer?

I'm writing a program that adds numbers. The program takes input from the user as an integer value and gives him a total of both numbers. But I want that when the user enters any character besides the number, a custom error is written to the console. How do you do that with if and else?
My code:
class Program
{
static void Main(string[] args)
{
double firstnum, secondnum, total;
Console.WriteLine("FIRST NUMBER");
firstnum = Convert.ToDouble(Console.ReadLine());
if (Console.ReadLine == char)
{
Console.WriteLine("error... error wrong keyword, enter only numbers...");
}
Console.WriteLine("SECOND NUMBER");
secondnum = Convert.ToDouble(Console.ReadLine());
total = firstnum + secondnum;
Console.WriteLine("TOTAL VALUE IS =" + total);
Console.ReadLine();
First read the string into a string variable. Then use TryParse to turn it into a number. It'll return false if the string is no valid number, which you can use to display your error.
var firstNumAsString = Console.ReadLine();
int firstNum;
if (!int.TryParse(firstNumAsString, out firstNum))
{
Console.WriteLine("error... error wrong keyword, enter only numbers...");
return;
}
If you want to throw an exception instead of just displaying an error, use int.Parse. It'll throw a FormatException or an OverflowException if the input isn't valid.

Categories