I would like to validate my input as bigger than or equal to 0 and as double. This is what i have so far:
string aBalBeginS;
double abalbeginVal;
Console.Write("Account Balance at the beginning: $");
aBalBeginS = Console.ReadLine();
abalbeginVal = double.Parse(aBalBeginS);
if (aBalBeginS == "" || abalbeginVal <= 0)
{
Console.WriteLine("Invalid data entered - no value redorded");
aBalBeginS = null;
}
How do i add to check if input is a number. I tried double.TryParse, but without luck.
You are on the right track with double.TryParse()
double abalbeginVal;
bool parsed = double.TryParse(aBalBeginS, out abalbeginVal);
if (parsed && abalbeginVal >=0.0)
{
// We're good
}
else
{
// Did not pass check
}
Found the solution:
Console.Write("Account Balance at the beginning: $");
aBalBeginC = Console.ReadLine();
//abalbeginVal = double.Parse(aBalBeginC);
if (double.TryParse(aBalBeginC, out abalbeginVal) == false || aBalBeginC == "" || abalbeginVal <= 0)
{
Console.WriteLine("Invalid data entered - no value redorded");
aBalBeginC = null;
}
Thx.
Related
So I have this code that will calculate the arithmetic mean. The user has to introduce random numbers, and when the input is "x" the code will stop and calculate the arithmetic mean. The code works fine if I introduce any numbers. However, if the first input is "x" I have to display "0". In the console, I get null ("") instead of 0.
The problem is the 'else' condition, the rest of the code works as expected. I tried to write the condition in different ways and even to put it in another block because I thought it is unreachable, but it is still null. I am not sure what I am missing.
Thank you in advance!
string line = Console.ReadLine();
double sum = 0;
double count = 0;
while (line != "x")
{
double number = Convert.ToInt32(line);
sum += number;
count++;
line = Console.ReadLine();
if (line == "x")
{
if (count > 0)
{
double ma = sum / count;
Console.WriteLine((float)ma);
}
else {
Console.WriteLine(0);
}
}
}
This worked for me. It wasn't clear what to do if user enters something other than 'x' or a number, so I put some error handling which ensures the app doesn't crash. I added a flag to detect if at least one valid number has been entered.
static void Main(string[] args)
{
string line = Console.ReadLine();
double sum = 0;
double count = 0;
bool numberHasBeenEntered = false;
while (line != "x")
{
double number;
//some error handling in case user enters something other than x or a number
try
{
number = Convert.ToInt32(line);
numberHasBeenEntered = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
sum += number;
count++;
line = Console.ReadLine();
if (line == "x")
{
if (count > 0)
{
double ma = sum / count;
Console.WriteLine((float)ma);
}
else
{
Console.WriteLine(0);
}
}
}
if (numberHasBeenEntered == false) Console.WriteLine(0);
}
If your first line is "X" then the code inside the while loop is not executed at all.
Use a do While loop
string line = Console.ReadLine();
double sum = 0;
double count = 0;
double number;
double ma;
do
{
if (line == "x")
{
if (count > 0)
{
line = Console.ReadLine();
ma = sum / count;
Console.WriteLine((float)ma);
}
else {
Console.WriteLine("0");
}
}
else
{
number = Convert.ToInt32(line);
sum += number;
count++;
}
}
while(line != "x")
Alright so in the book im reading its telling me to write a program that asks the user for two multiplication numbers and then it will print out whether the result should be positive or negative.
The rule is that i cannot take two numbers and multiply them, and then check if the result is greater than or less than zero. Instead if the two numbers have the same sign (both positive or both negative) the result is positive. If they have different signs, the result is negative.
I did it like this ( also i added int anresult = first * second; <- do i need that?) because if i remove it it still works, but the book wants it in multiplication. so im not sure if that piece of code is doing anything at all
Console.WriteLine("Enter First Nuumber: ");
string firstAsString = Console.ReadLine();
int first = Convert.ToInt32(firstAsString);
Console.WriteLine("Enter Second Nuumber: ");
string secondAsString = Console.ReadLine();
int second = Convert.ToInt32(secondAsString);
int anresult = first * second;
if (first >= 0 && second > 0 || first < 0 && second < 0)
Console.WriteLine("Your number will be Positive");
else
Console.WriteLine("Your number will be negative");
Console.ReadLine();
But the book did it like this
Console.WriteLine("Enter First Nuumber: ");
string firstAsString = Console.ReadLine();
int first = Convert.ToInt32(firstAsString);
Console.WriteLine("Enter Second Nuumber: ");
string secondAsString = Console.ReadLine();
int second = Convert.ToInt32(secondAsString);
bool firsNumberPositive;
bool secondNumberPositive;
if (first > 0) {
firsNumberPositive = true;
}
else
{
firsNumberPositive = false;
}
if (second > 0)
{
secondNumberPositive = true;
}
else
{
secondNumberPositive = false;
}
if (firsNumberPositive && secondNumberPositive || !firsNumberPositive && !secondNumberPositive)
Console.WriteLine("Answer Is Positive");
else
if (!firsNumberPositive && secondNumberPositive || firsNumberPositive && !secondNumberPositive)
Console.WriteLine("Answer Is Negative");
Console.ReadLine();
isnt my way the same as the books way? because the book shows
if (first > 0) {
firsNumberPositive = true;
}
which is using the numbers just like i am to display positive and negative
heres mine, same thing?..
if (first >= 0 && second > 0 || first < 0 && second < 0)
Console.WriteLine("Your number will be Positive");
else
Console.WriteLine("Your number will be negative");
The solution presented in the book doesn't consider the condition where the input is 0, so it will behave differently than the code you wrote.
Your solution does not output the same result as the one in the book. Just try it with both first and second 0. Your code will say the result is negative while the book's solution will say it is positive.
In my opinion, 0 is neither a positive nor negative number and should be treated separately. So here's my solution:
if (first == 0 || second == 0) {
Console.WriteLine("The result is 0");
} else if ((first > 0) != (second > 0)) { // here, it might look a little weird but I'm just checking whether the signs are the same.
Console.WriteLine("The result is negative");
} else {
Console.WriteLine("The result is positive");
}
Thanks for your feedback. I'm still getting an out of range exception. I'm debugging but can't understand why I'm getting the exception. If an int is higher than a certain other int it should work. Does it have anything to do with the length.Count?
UPDATED Code
do
{
Console.Write("Input the element that you want to exclude from the list: ");
result = int.TryParse(Console.ReadLine(), out delSelection);
tempInputDelInt = (int)(tempList[delSelection]);
tempInputDelStr = Convert.ToString(tempInputDelInt);
if (result == true && tempInputDelInt >= 0 && tempInputDelInt < tempList.Count)
{
tempList.RemoveAt(delSelection);
Console.WriteLine("\nYou've deleted the temperature " + tempInputDelStr + " from index " + delSelection);
success = false;
Console.ReadKey(true);
Console.Clear();
}
else if (result == true && tempInputDelInt >= tempList.Count || tempInputDelInt < 0)
{
Console.WriteLine("You've input a number that's outside the list. Input a digit between 0 and " + (tempList.Count - 1) + ".\n");
success = true;
Console.ReadKey(true);
}
else if (result == false)
{
Console.WriteLine("\nYou didn't input a digit, try again!\n");
success = true;
Console.ReadKey(true);
}
} while (success);
success = false;
I'm having some problems with the validation of the first else if statement. I want to catch the cases when a value outside of the array is input, but I don't manage to.
I've done a practically identical program with array.Length with success.
Is there any difference between array.List and list.Count? Is that's the problem?
Thanks in advance for your help!
do
{
Console.Write("Input the element that you want to exclude from the list: ");
result = int.TryParse(Console.ReadLine(), out delSelection);
tempInputDel = Convert.ToString(tempList[delSelection]);
if (result == true && delSelection >= 0 && delSelection < tempList.Count)
{
tempList.RemoveAt(delSelection);
Console.WriteLine("\nYou've deleted the temperature " + tempInputDel + " from index " + delSelection);
Console.ReadKey(true);
Console.Clear();
}
else if (result == true && delSelection >= tempList.Count || delSelection < 0)
{
Console.WriteLine("You've input a number that's outside the list. Input a digit between 0 and " + (tempList.Count - 1) + ".\n");
}
else if (result == false)
{
Console.WriteLine("\nYou didn't input a digit, try again!");
Console.ReadKey(true);
}
} while (result == false);
Change this
tempInputDelInt = (int)(tempList[delSelection]);
to this
tempInputDelInt = (int)delSelection;
Whatever number the user enters, you're using that as the index to determine which item to delete. So it's not a value you get from tempList.
I am assuming that your out-of-range exception happens here:
tempInputDel = Convert.ToString(tempList[delSelection]);
You cannot do this before checking, if delSelection is inside range of tempList. Move it inside first if block.
General advice:
You can use a debugger to go from statement to statement step-by-step to find the exact source code position where (e.g.) an exception is thrown.
class Program
{
static void Main(string[] args)
{
string choice = string.Empty;
do
{
start:
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if (number < 1000)
{
switch (conversion)
{
case true:
while (number <= output)
{
Console.Write(number + " ");
number += 2;
}
break;
case false:
Console.WriteLine("ERROR: INVALID INPUT!");
goto start;
}
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
return;
}
do // Here is the beginning of the do code
{
Console.WriteLine("\n Do you want to continue - Yes or No");
choice = Console.ReadLine();
if (choice.ToUpper() != "YES" && choice.ToUpper() != "NO")
{
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
} while (choice.ToUpper() != "YES" && choice.ToUpper() != "NO");
} while (choice.ToUpper() == "YES");
}
}
I'm using several do while loops in this statement however I'm trumped on how I would put in a loop "ERROR INVALID INPUT:" result when a user puts in anything other than the limits of the assigned integers (i.e. putting decimals or fractions) or if they put a string. I simply used goto because I'm having trouble finding out where to put the do while loop statement. If someone could simply show me how I might replace that one goto with a do while loop then I would be very greatful. (Note if you show me ways I could optimize my code better since I'm still new I probably won't understand it but your welcome to give it your best shot!)
Short answer:
The keyword continue means to go back to the beginning of the loop. Note that this will recheck the loop condition and break if it is false. Also, most people find do-while loops less readable (and they are really rarely necessary), so try using while loops instead.
There is also the keyword break which will simply exit the loop. (not just for switch-case!)
A more readable version would look something like this:
string userAnswer = "yes";
// while is usually more readable than do-while
while (userAnswer == "yes")
{
Console.WriteLine("Please input a number for it to be counted!");
int number;
// Ask for new input until the user inputs a valid number
while (!int.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("Invalid number, try again");
}
if (number < 1000)
{
// Print from 0 to number, jumping in 2's
for (int i = 0; i <= number; i += 2)
Console.WriteLine(i + " ");
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
continue; // Jump back to the start of this loop
}
Console.WriteLine("Continue? (Yes / No)");
userAnswer = Console.ReadLine().ToLower();
// Ask for new input until the user inputs "Yes" or "No"
while (userAnswer != "yes" && userAnswer != "no")
{
Console.WriteLine("Invalid input. Continue? (Yes / No)");
userAnswer = Console.ReadLine().ToLower();
}
}
Hey I'll post some code that may help and offer some advice. Basically declare a bool named 'loopCompleted' which will continue the do while loop until you set it to true. The downside is that it will not instantly exit the loop like return/goto/etc but this is not a problem in most cases.
You may want to use if/else instead of switch(conversion), its sort of interesting to see it done that way but its a bit over the top :)
If Int.TryParse() doesnt already return false for fractional values (e.g. [15.08] returns [true] with [15] ). Then you can store Console.ReadLine() before using TryParse, then use stringName.Contains() to check for the '.' Basically, if the conversion succeeds you also check if it contained the decimal point.
Another way to check is to do float.TryParse() then check if it is a fractional value.
bool fraction = false;
if( number % 1.0f > 0)
fraction == true;
% is called modulus, it returns the remainder of A / B
If a number has a remainder when divided by 1 it must be a fractional value.
//start:
bool loopCompleted = false;
do
{
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if (conversion && number < 1000)
{
while (number <= output)
{
Console.Write(number + " ");
number += 2;
}
loopCompleted = true;
}
else
{
if(conversion == false)
{
Console.WriteLine("ERROR: INVALID INPUT!");
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
}
}
} while(!loopCompleted)
I have written my codes and i want to validate it in such a way thet it will only allow intergers to be inputed and not alphabets. Here is the code, please I will love you to help me. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace minimum
{
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = Convert.ToInt32(Console.ReadLine());
if (a < b)
{
if (a < c)
{
Console.WriteLine(a + "is the minimum number");
}
}
if (b < a)
{
if (b < c)
{
Console.WriteLine(b + "is the minimum number");
}
}
if (c < a)
{
if (c < b)
{
Console.WriteLine(c + "is the minimum number");
}
}
Console.ReadLine();
}
}
}
You should test if it's an int instead of converting in right away.
Try something like :
string line = Console.ReadLine();
int value;
if (int.TryParse(line, out value))
{
// this is an int
// do you minimum number check here
}
else
{
// this is not an int
}
Simply call Readline() and loop with Int.TryParse until the user inputs a valid number :)
int X;
String Result = Console.ReadLine();
while(!Int32.TryParse(Result, out X))
{
Console.WriteLine("Not a valid number, try again.");
Result = Console.ReadLine();
}
Hope that helps
To get the console to filter out alphabetical keystrokes you have to take over input parsing. The Console.ReadKey() method is fundamental to this, it lets you sniff the pressed key. Here's a sample implementation:
static string ReadNumber() {
var buf = new StringBuilder();
for (; ; ) {
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && buf.Length > 0) {
return buf.ToString() ;
}
else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) {
buf.Remove(buf.Length-1, 1);
Console.Write("\b \b");
}
else if ("0123456789.-".Contains(key.KeyChar)) {
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else {
Console.Beep();
}
}
}
You could add, say, Decimal.TryParse() in the if() statement that detects the Enter key to verify that the entered string is still a valid number. That way you can reject input like "1-2".
Do not Convert the input from the user immediately. Put it in a string and use Int32.TryParse(...) to find out whether or not a number was entered. Like this:
int i;
string input = Console.ReadLine();
if(Int32.TryParse(input, out i))
{
// it is a number and it is stored in i
}
else
{
// it is not a number
}
Note that
if (a < b) {
if (a < c) {
is equivalent to
if (a < b && a < c) {
and that this latter form introduces less nesting and is more readable, particularly if your code grows more complex. Also, you should probably never use Convert.ToInt32 - it has a particularly ill-conceived and surprising corner case; and it's also less type-safe than int.Parse which is the superior choice where possible - or int.TryParse when you're unsure whether the string is valid. Basically, avoid Convert.... wherever possible.
string Temp;
int tempInt,a;
bool result=false;
while ( result == false )
{
Console.Write ("\n Enter A Number : ");
Temp = Console.ReadLine ();
result = int.TryParse (Temp, out tempInt);
if ( result == false )
{
Console.Write ("\n Please Enter Numbers Only.");
}
else
{
a=tempInt;
break;
}
}
My preferred solution would be:
static void Main()
{
Console.WriteLine(
(
from line in Generate(()=>Console.ReadLine()).Take(3)
let val = ParseAsInt(line)
where val.HasValue
select val.Value
).Min()
);
}
static IEnumerable<T> Generate<T>(Func<T> generator) {
while(true) yield return generator();
}
static int? ParseAsInt(string str) {
int retval;
return int.TryParse(str,out retval) ? retval : default(int?);
}
Of course, depending on the specification (should invalid number be retried?), it may need to be tweaked.
Double/Float:
I'm just extending #Hans Passant answer (Taking care of DecimalSeparator and "-"):
static double ReadNumber()
{
var buf = new StringBuilder();
for (; ; )
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && buf.Length > 0)
{
Console.WriteLine();
return Convert.ToDouble(buf.ToString());
}
else if (key.Key == ConsoleKey.Backspace && buf.Length > 0)
{
buf.Remove(buf.Length - 1, 1);
Console.Write("\b \b");
}
else if (System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.Contains(key.KeyChar) && buf.ToString().IndexOf(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator) == -1)
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else if ("-".Contains(key.KeyChar) && buf.ToString().IndexOf("-") == -1 && buf.ToString() == "")
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else if ("0123456789".Contains(key.KeyChar))
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else
{
Console.Beep();
}
}
}
var getInput=Console.ReadLine();
int option;
//validating input
while(!int.TryParse(getInput, out option))
{
Console.WriteLine("Incorrect input type. Please try again");
getInput=Console.ReadLine();
}
Try This Simple
try
{
string x= "aaa";
Convert.ToInt16(x);
//if success is integer not go to catch
}
catch
{
//if not integer
return;
}