C# How set a non-numeric value to 0 - c#

I have to write a code that will ask for 3 integers values and find the greatest one. However, if the user enters a non numeric value this must have the value of zero. So far i wrote this
int a, b, c;
Console.WriteLine("Enter value 1:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value 2:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value 3:");
c = Convert.ToInt32(Console.ReadLine());
if (a > b && a > c)
{
Console.WriteLine("The greatest value is: {0}", a);
}
if (b > a && b > c)
{
Console.WriteLine("The greatest value is: {0}", b);
}
if (c > a && c > b)
{
Console.WriteLine("The greatest value is: {0}", c);
}
This code works only with numbers.
My problem is that i can't make a non numeric input have the value of zero.
I tried using string instead of int, so there is no error but i can not make use ">" with strings in the if statements and i also tried using as default, because when is default so it is zero.
Thank you

You can just replace:
x = Convert.ToInt32(Console.ReadLine());
With...
int.TryParse(Console.ReadLine(), out int x);
If the input can't be parsed, x will end up being 0.

I think you can create a function that does the try catch, in this way you print a message saying that the input was not a number.
static int Check(string input)
{
int result;
try
{
result = Convert.ToInt32(input);
}
catch (FormatException e)
{
Console.WriteLine("Input not integer, the value assigned is 0");
result = 0;
}
return result;
}
For implementing you just call:
a = Check(Console.ReadLine());

Related

A program that gets 3 digits and outputs the smallest one in C# Console App

How can I make a program in C# that gets 3 digits from the user and outputs the smallest one? It's gonna be as a Console App.
I tried this and gave me an error (I may be stupid):
if (a<b<c)
{
min=a;
Console.WriteLine("Min: " + min);
I don't now what else should I do, I'm new to C#.
There's nothing wrong with being new, and you aren't stupid just because you aren't sure how something works.
Think of it like this:
We need to have a variable to hold this minimum value:
int min;
First, you need to compare two values to get the smallest between them:
if (a < b)
min = a;
else
min = b;
Now that you have the minimum between those two, compare that value to your third input:
if (c < min)
min = c;
If c is less than the current min value, you adjust to c, otherwise you already had your minimum value in the first comparison.
Here is a full example for you to play with as well:
int a = 4;
int b = 2;
int c = 1;
int min;
if (a < b)
min = a;
else
min = b;
if (c < min)
min = c;
Console.WriteLine("Lowest value is {0}", min);
Try this.
if (a < b && a < c)
{
Console.WriteLine("Min: " + a);
}
else if (b < c)
{
Console.WriteLine("Min: " + b);
}
else
{
Console.WriteLine("Min: " + c);
}
Here's a solution that should work:
int a, b, c, min;
Console.WriteLine("Please enter three digits:");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
c = int.Parse(Console.ReadLine());
min = Math.Min(Math.Min(a, b), c);
Console.WriteLine("Min: " + min);
Just run this code and write if you want me to explain smth. It will be nice if you mark this answer as correct if that's helped you
#region Begin Message
string s = "\"s\"";
Console.WriteLine(#$"Here is example of the code.
Please contact me if you did not understand smth.
You should write as many numbers as u wanna, the program returns numbers in ascending order.
Write {s} to stop
");
#endregion
#region Main Part
List<float> numbers = new List<float>();
while (true)
{
Console.WriteLine($"{numbers.Count + 1} number: ");
string input = Console.ReadLine();
if (input.ToLower().Contains("s"))
{
Console.WriteLine(SortNumbers(numbers) ?? "There are no numbers created");
break;
}
else
{
try
{
float number = float.Parse(input);
numbers.Add(number);
}
catch (Exception ex) { Console.WriteLine("You should write a number \n"); }
}
}
#endregion
string? SortNumbers(List<float> numbers)
{
numbers.Sort();
string? returnedNumbers = null;
if (numbers.Count != 0)
{
returnedNumbers += "\nNumbers: ";
for (int i = 0; i < numbers.Count; i++)
{
returnedNumbers += $"{numbers[i]}, ";
}
}
return returnedNumbers;
}

Creating a "warning" when trying to calculate X/0

I want to make a calculator that asks what you want to do, e.g. add, subtract, etc. It should then use if-statements to perform the different kinds of calculations.
But now when I have gotten to division, I'm wondering how to handle division by 0. I want the program to warn the user when he/she enters a 0, saying something like "sorry you can't divide by 0".
I still want it to calculate the result if the denominator isn't 0.
The error i get is that i can't write:
if (Num02 == "0") because I can't use ints or doubles etc.
How do I fix this in a nice way to show my class/teacher next week?
Here's my code:
using System;
namespace Calculator
{
class MainClass
{
static void Main(string[] args)
{
Start:
int Num01;
int Num02;
string Answer;
Console.WriteLine("What do you want to do?");
Answer = Console.ReadLine();
if (Answer == "Division")
{
Console.WriteLine("Write number");
Num01 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Divided by?");
Num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(Num01 + "/" + Num02 + "=" +
(Num01 / Num02));
}
}
}
}
the error i seem to get is that i cant write:
"if (num02 == "0")" because i cant use ints or doubles etc.
You were most certainly on the right track. By adding quotes around the "0", you were comparing a variable of type int (Num02) with a string. Instead, use a literal 0 (without quotes):
if (Num02 == 0)
{
// print warning here
}
else
{
// do division and print result
}
I suggest extracting method for the user input (where we can check syntax - what if user put bla-bla-bla instead of number, extra condition(s) - we don't accept 0 as a second number etc.):
private static int ReadValue(string title,
Func<int, bool> extraCondition = null,
string extraConditionText = null) {
int result;
while (true) { // keep on asking until correct input provided
Console.WriteLine(title);
if (!int.TryParse(Console.ReadLine(), out result)) // syntax check
Console.WriteLine("Syntax error, please, input integer value");
else if (extraCondition != null && !extraCondition(result)) // extra check if any
Console.WriteLine(string.IsNullOrEmpty(extraConditionText)
? "Incorrect value"
: extraConditionText);
else
return result;
}
}
Then you can put
static void Main(string[] args) {
while (true) {
int Num01;
int Num02;
Console.WriteLine("What do you want to do?");
string Answer = Console.ReadLine().Trim();
if (string.Equals(Answer, "Quit", StringComparison.OrdinalIgnoreCase)) {
break;
}
else if (string.Equals(Answer, "Division", StringComparison.OrdinalIgnoreCase)) {
Num1 = ReadValue("Write number");
Num2 = ReadValue("Divided by?", x => x != 0, "Sorry you can't divide by 0");
Console.WriteLine($"{Num1} / {Num2} = {Num1 / Num2}");
}
else {
Console.WriteLine("Sorry, it's an incorrect option");
}
}
}

Unexpected result at summing numbers using a while loops in console application

I am trying to make a program to sum numbers until the user enter OK.
The program make the sum, but return a bad result.
i'm not sure where is my error...
int sum = 0;
Console.WriteLine("Enter number:");
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
{
sum += num;
}
Console.WriteLine(sum);
you don't keep the number the use enter in the while loop.
you need to input the readline to a variable.
var num = Console.Readline();
sum += num; //parse first
Inside your while loop you need to update num:
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
{
num = Int32.Parse(Console.ReadLine());
sum += num;
}
Also just as a note, if you need your program to be a little safer, you can you use the following:
int num;
if(Int32.TryParse(Console.ReadLine(), out num)) {
//do something..
}
else {
//do something else.. like end program, throw exception etc.
}
Int32.TryParse:
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the conversion
succeeded
This way you can do something in the instance that the input string was not a valid conversion. Example: if someone input cat, which can not be converted to an int, it would crash your program without the TryParse.
You need to input the number once per iteration, and store it each time. So each value retrieved from Console.ReadLine() needs to be captured in an assignment statement, then converted to a number if it is not "OK".
I think you're after this:
int sum = 0;
string input;
Console.WriteLine("Enter number: ");
while ((input = Console.ReadLine()) != "OK")
{
int inputNum = Convert.ToInt32(input);
sum += num;
Console.WriteLine("Enter number: ");
}
The statement (input = Console.ReadLine() assigns the user input to the input variable, then the assignment statement returns the value of input. Then that value is compared against OK.
An alternative way to get input, then check it is:
Console.WriteLine("Enter number: ");
input = Console.ReadLine()
while (input != "OK")
{
...
Console.WriteLine("Enter number: ");
input = Console.ReadLine()
}
int sum = 0;
Console.WriteLine("Enter number:");
int num = int.Parse(Console.ReadLine());
while (sum< num)
{
sum++;
}
Console.WriteLine(sum);

Ending a loop by sentinel and parsing an input string as an integer

I am trying to continuously ask user for a number between 300-850. When the user enters a valid number, add it to the total and ask again. If the number is invalid, display an error. Before program ends, display the average of total number by amount of times of input. End program if user enters a sentinel value. I don't know how to check if user enters a sentinel value.
using System;
class CreditScores
{
static void Main()
{
var iterations = 0;
double total = 0;
int sum = 0;
double average = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentinel value reached.
while (iterations < 1000)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
int input = int.Parse(Console.ReadLine());
//not sure how to check if input is a number or not
if(input == integer)
{
if( input < 850 && input > 300 )
{
total +=input;
}
}
else
{
break;
}
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
average = total / count;
Console.WriteLine("The average is {0}", average);
}
}
Modification/fix of Your Method
Also, I would read all the way to the end for the more robust method you could use.
First thing I would change:
while (iterations < 1000)
{
...
}
To this (which we are not done yet, read to the end):
while (input != "calculate") // or some other string
{
...
}
Then, before the while starts, make input a string.
string input = "";
while (input != "calculate") // or some other string
{
...
}
Now, we declared an input variable that is already an int later on. Let's fix that.
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Now, we need to put it together and do some cleaning.
int total = 0;
int numbersEntered = 0;
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
{
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
{
total += value;
numbersEntered++;
}
}
else
{
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
}
Console.WriteLine("Total is {0}", total);
double average = (double)total / numbersEntered;
Console.WriteLine("The average is {0}", average);
(I know, long answer. But it should help you step through the problem in the future. Also, I wrote this all by memory, I can't guarantee it will compile.)
Update: just tested it, works as expected.
A more Robust Method
Lastly, and this is really the coolest method in my opinion, use a List<int> and some extension methods.
List<int> values = new List<int>();
string input = "";
while (input != "calculate")
{
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value = 0;
if (int.TryParse(input, out value))
// Clearly it's a valid integer at this point
if (value < 850 && value > 300)
values.Add(value);
else
{
// Was outside our range
}
else
// Wasn't a number, might be our sentinel.
if (input == "calculate")
break;
else
{
// Throw an error or something.
}
}
Console.WriteLine("Total is {0}", values.Sum());
Console.WriteLine("The average is {0}", values.Average());
Advantages to this method? It saves a list of the values entered, allowing you to do more with them that you cannot do with the method you currently have. It also uses the int.Sum() and int.Average() extension methods rather than your own math.
What is this int.TryParse(string, out int) sorcery?
The int.TryParse(string, out int) method (as defined by MSDN) will take an input string, and return a boolean value that indicates if it would make a valid int structure or not.
In the case that the string is a valid int, then the int parameter is filled with the integer representation of the string.
I.e.:
string myString = "100";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return true and print: myString was a valid int: 100.
Example 2:
string myString = "blah";
int value = 0;
if (int.TryParse(myString, out value))
Console.WriteLine("myString was a valid int: {0}", value);
else
Console.WriteLine("myString was not a valid int.");
This version will return false, and print myString was not a valid int.. The value variable would also be 0.
Warning:
When using int.TryParse(string input, out int value), do not rely on the value parameter as 0 to indicate failure. If the input is "0", then the value will also be 0, and the method will return true.
You want to set the condition of your while loop to something that a user can trigger as false (the sentinel).
Then put a for loop inside that if you want to do a set number of iterations, for loops are better for situations where you know how many iterations you're doing.
BUT if you want to stick to while loops only, here's a quick code snippet you could use:
while (input != 0 && iterations < 1000) //or some sentinel value you choose
{
//Your logic here, now the loop will quit if if the user enters 0
//OR you run out of iterations
}
using System;
class CreditScores
{
static void Main()
{
double total = 0;
int sum = 0;
int count = 0;
Console.WriteLine("Enter value between 300 to 850.");
int first = int.Parse(Console.ReadLine());
//trying to get it to stop when sentihel value reached.
for (iterations = 0; iterations < 1000; iterations++)
{
Console.WriteLine("Enter value between 300 to 850.");
int input;
// Check number is integer
if (int.TryParse(Console.ReadLine(), out input)
{
if(input > 300 && input < 850)
{
total +=input;
}
}
else
{
break;
}
count++;
}
total = sum + total;
Console.WriteLine("Total is {0}", total);
double average = total/count;
Console.WriteLine("The average is {0}", average);
Console.ReadLine(); // Either this or run with Ctrl-F5
}
}
The behaviour would be to add the totals until the user entered something that couldn't be parsed, and then exit.
Does this work?
string sentinalValue = "done";
string input = "";
while (iterations < 1000 && input != sentinalValue)
{
iterations++;
Console.WriteLine("Enter value between 300 to 850.");
input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if( value < 850 && value > 300 )
{
total +=input;
}
}
else
{
Console.WriteLine("That is not a number!");
}
}

Checking user input in C#

I just wrote my first C# console application, I am still a beginner. Anyway, I tried the code below and it seems to work, its for solving quadratic equations. I'd like to add code for a situation whereby a user inputs a string instead of an integer and give an error message any ideas as to how to implement this?
namespace Quadratic_equation
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("welcome to seyi's quadratic calculator!!!");
Console.Write("a:");
double a = Convert.ToInt32(Console.ReadLine());
Console.Write("b:");
double b = Convert.ToInt32(Console.ReadLine());
Console.Write("c:");
double c = Convert.ToInt32(Console.ReadLine());
if ((b * b - 4 * a * c) < 0) {
Console.WriteLine("There are no real roots!");
}
else {
double x1 = (-b + Math.Sqrt((b*b)-4*a*c)) /2*a;
double x2 = (-b + Math.Sqrt((b*b)-4*a*c)) /2*a;
Console.WriteLine("x:{0}",x1);
Console.WriteLine("y:{0}",x2);
}
Console.ReadKey();
}
}
}
You can use Int32.TryParse method to check your string is a valid integer or not. This method returns a boolean value for your conversation is succeed or not.
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the conversion
succeeded.
And I don't understand why you want to keep as double the return value of Convert.ToInt32 method. These factors (a, b, c) should be integer, not double.
int a;
string s = Console.ReadLine();
if(Int32.TryParse(s, out a))
{
// Your input string is a valid integer.
}
else
{
// Your input string is not a valid integer.
}
This Int32.TryParse(string, out int) overload uses NumberStyle.Integer as default. That means your string can have one of these;
Trailing white spaces
Leading white spaces
Leading sign character
Check out int.TryParse
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
Use a try-catch block in a do-while loop:
bool goToNextNum = false;
do
{
try
{
double a = Convert.ToInt32(Console.ReadLine());
goToNextNum = true;
}
catch
{
Console.WriteLine("Invalid Number");
}
} while (goToNextNum == false);
This will loop until a is a valid number.

Categories