TryParse doesnt work for initial values of if statements - c#

I am using TryParse for the code below, but when I put 1 or 2 the program doesnt continue.
int x = -1;
bool noRecords = true;
do
{
Console.WriteLine("1.Add Data");
Console.WriteLine("2.Show Data");
Console.WriteLine("0.Exit");
//x = Convert.ToInt32(Console.ReadLine());
if (x == 1)
{
Helper.ShowAddMenu(noRecords);
}
if (x == 2)
{
Helper.ShowDataMenu();
}
} //while (x != 0);
while (!int.TryParse(Console.ReadLine(), out x) || x > 2 || x < 0);

Your while loop is wrong if you want it to continue when you enter 1 or 2. The order of operations during execution of that expression in your while loop will be:
You enter the value 1
Console.Readline() will return the string "1"
int.TryParse("1", out x) will set x to 1 and will return true
!true evaluates to false
x > 2 evaluates to false because x is 1
x < 0 evaluates to false because x is 1
therefore, your while loop is while(false || false || false)
EDIT: Given the discussion in the comments below, I believe OPs use case would be best served with a code structure more like the following. Trying to cram it all into the while clause is going to be confusing.
static void Main()
{
ShowMenu();
while (true)
{
int x;
if (!int.TryParse(Console.Readline(), out x))
ShowMenu();
else if (x == 0)
break;
else if (x == 1)
Helper.ShowAddMenu(noRecords);
else if (x == 2)
Helper.ShowDataMenu();
}
}
static void ShowMenu()
{
Console.WriteLine("1.Add Data");
Console.WriteLine("2.Show Data");
Console.WriteLine("0.Exit");
}

Change !int.TryParse to just int.TryParse. TryParse returns true on success, not false.
See here dotnetfiddle.net/6JCoPQ

Related

why does "not equal" with "or" doesn't working in c# (check if number is binary)?

I really don't why it doesn't working. (it should check if number is binary)
why the operators doesn't apply right?
using System;
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine(IsBin(100));
Console.WriteLine(IsBin(10011012));
Console.WriteLine(IsBin(10911010));
}
public static bool IsBin(long num)
{
while (num > 0)
{
if ((num % 10) != 1 || (num % 10) != 0)
{
return false;
}
num /= 10;
}
return true;
}
}
At least one expression on each side of the || is always true. So the result of the expression using || is always true.
You can do your check in one expression using a ! (not), but this will make your code less readable, so I suggest store the result in a temporary variable to improve readability.
You could be using:
var isZeroOrOne = (num % 10) == 1 || (num % 10) == 0)
if (!isZeroOrOne)
{
return false;
}
num /= 10;
Too Long, Won't Read: Use && instead of || in your if statement.
And for those, who wants to know why:
OR operator(||) returns true when at least one side is true. So 100%10=0 and 0!=1 is true so the whole or statement will return true and program will jump into your if statement.
AND operator(&&) returnstrue only when both sides are true. 0!=1 is true but 0!=0 is false so the && operator will return false and your if will not be executed.
Is it clear?

How to take into the account part of condition inside the condition only if some value is true

I'm trying to understand how it is possible to put condition inside condition itself.
for example, below I'm showing wrong unreal code, but clear to understand what I'm asking for without extra words:
if (a == 1 && if (b == 1) { c >= 5 })
{
/// process
}
So condition c >= 5 must be taken into the account for process only in case if b == 1 which must be exist inside one statement without using of separate function with separate conditions or as condition after condition.
Question is how take part of condition into the account inside the condition only in case if some value is true and avoid it if false and read only a == 1.
EDIT based on answer below:
int a = 1;
int b = 0;
int c = 6;
if (a == 1 && (b != 0 || c >= 5))
{
Console.WriteLine("yes");
if (c > 5)
{
Console.WriteLine("taken into the account");
}
}
else
{
Console.WriteLine("no");
}
in both cases int b = 1; and int b = 0; result is:
yes
taken into the account
desired result:
in case of int b = 1; :
yes
taken into the account
and in case of int b = 0;:
yes
if (a == 1 && (b != 1 || c >= 5 ))
Here, c >= 5 will only be evaluated when b==1.
In c# && is a short circuiting operation so b==1 will not be evaluated if a==1 does not evaluate to true.

C# for case in string(easy)

so I have this code. I need to generate a for loop that checks all the characters in the string and checks if they are all valid(So numbers from 0->7). But I don't know how to write it, I tried something but it didn't work. Here are the examples:user enters: 77, code works, user enters 99, code doesn't work, user enters 5., code doesn't work, etc..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NALOGA1
{
class Program
{
static string decToOct(int stevilo)//v mojon primere 7
{
string izhod = "";
//7>0 DRŽI
while (stevilo > 0)
{
//izhodi se dodeli ostanek deljenja z 8 keri se spremeni v string
izhod = (stevilo % 8) + izhod;
//7/8;
stevilo /= 8;
}
return izhod;
}
static int Octtodesetisko(string stevilo)
{
double vsota = 0;
for (int i = stevilo.Length - 1; i >= 0; i--)
{
int stevka = stevilo[i] - '0';
vsota += (stevka * Math.Pow(8, i));
}
return (int)vsota;
}
static void Main(string[] args)
{
//3 podprogram-in progress
string prvastevilka = Console.ReadLine();
int prvasprememba = Int32.Parse(prvastevilka);
if (prvasprememba > 0)
{
Console.WriteLine(decToOct(prvasprememba));
}
else
{
Console.WriteLine("Napaka");
}
string drugastevilka = Console.ReadLine();
int drugasprememba = Octtodesetisko(drugastevilka);
foreach (char znak in drugastevilka)
{
if(znak!=1 || znak!=2 || znak!=3 || znak!=4 || znak!=5 || znak!=6 || znak!=7)
{
Console.WriteLine("Napaka");
}
else
{
Console.WriteLine("dela :D");
}
}
Console.ReadKey();
}
}
}
Personally, I would take advantage of the LINQ Enumerable.All method to express this in a very concise and readable way:
if (str.Any() && str.All(c => c >= '0' && c <= '7'))
{
Console.WriteLine("good");
}
else
{
Console.WriteLine("bad");
}
EDIT: No LINQ
It's not hard to translate what the LINQ Enumerable.All method does to a normal loop. It's just more verbose:
bool isValid = true;
foreach (char c in str)
{
if (c < '0' || c > '7')
{
isValid = false;
break;
}
}
if (str.Length != 0 && isValid)
{
Console.WriteLine("good");
}
else
{
Console.WriteLine("bad");
}
Firstly, there seems to be a mistake in the line
if(znak!=1 || znak!=2 || znak!=3 || znak!=4 || znak!=5 || znak!=6 || znak!=7)
I guess it should read
if(znak!='1' || znak!='2' || znak!='3' || znak!='4' || znak!='5' || znak!='6' || znak!='7')
which should be compressed to
if (znak >= '0' && znak <= '7')
You can use linq instead of the for loop here like this:
if (drugastevilka.All(c => c >= '0' && c <= '7')
Console.WriteLine("dela :D");
else
Console.WriteLine("Napaka");
But the best solution is probably to use a regular expression:
Regex regex = new Regex("^[0-7]+$");
if (regex.IsMatch(drugastevilka))
Console.WriteLine("dela :D");
else
Console.WriteLine("Napaka");
Edit: the linq solution shown accepts empty strings, the regex (as shown) needs at least 1 character. Exchange the + with a * and it will accept empty strings, too. But I don't think you want to accept empty strings.
You are messing up with the datatype
Can you try with below code
static string decToOct(int stevilo)//v mojon primere 7
{
int izhod = 0;
//7>0 DRŽI
while (stevilo > 0)
{
//izhodi se dodeli ostanek deljenja z 8 keri se spremeni v string
izhod = (stevilo % 8) + izhod;
//7/8;
stevilo /= 8;
}
return (izhod.ToString());
}
What about something like this?
class Program
{
static void Main(string[] args)
{
string someString = "1234567";
string someOtherString = "1287631";
string anotherString = "123A6F2";
Console.WriteLine(IsValidString(someString));
Console.WriteLine(IsValidString(someOtherString));
Console.WriteLine(IsValidString(anotherString));
Console.ReadLine();
}
public static bool IsValidString(string str)
{
bool isValid = true;
char[] splitString = str.ToCharArray(); //get an array of each character
for (int i = 0; i < splitString.Length; i++)
{
try
{
double number = Char.GetNumericValue(splitString[i]); //try to convert the character to a double (GetNumericValue returns a double)
if (number < 0 || number > 7) //we get here if the character is an int, then we check for 0-7
{
isValid = false; //if the character is invalid, we're done.
break;
}
}
catch (Exception) //this will hit if we try to convert a non-integer character.
{
isValid = false;
break;
}
}
return isValid;
}
}
IsValidString() takes a string, converts it to a Char array, then checks each value as such:
Get the numeric value
Check if the value is between 0-7
GetNumericValue will fail on a non-integer character, so we wrap it in a try/catch - if we hit an exception we know that isValid = false, so we break.
If we get a valid number, and it's not between 0-7 we also know that isValid = false, so we break.
If we make it all the way through the list, the string is valid.
The sample given above returns:
IsValidString(someString) == true
IsValidString(someOtherString) == false
IsValidString(anotherString) == false

Index array out of bounds

if (testModetrue)
{
try
{
Console.Write("What number do you want the roll to be set to? (1-6)");
string diceString = Console.ReadLine();
int diceCheck = int.Parse(diceString);
if ((diceCheck >= minDiceValue) || (diceCheck <= maxDiceValue))
{
diceNo = int.Parse(diceString);
}
else if ((diceCheck <= minDiceValue) || (diceCheck >= maxDiceValue))
{
Console.WriteLine("Please enter a number between 1-6.");
break;
}
}
catch (Exception)
{
Console.WriteLine("An error has occured.");
return;
}
}
This code checks to see whether the answer given doesn't go past 6 or below 1, however whenever I run it, it does it anyway then it throws the out of array error, anybody help?
int diceCheck = int.Parse(diceString);
if ((diceCheck >= minDiceValue) || (diceCheck <= maxDiceValue))
{
diceNo = int.Parse(diceString);
}
This conditional should be AND rather than OR. Also, since you're parsing the string before the conditional, you don't need to do it inside it, so you should change that part to:
int diceCheck = int.Parse(diceString);
if (diceCheck > maxDiceValue && diceCheck < minDiceValue)
{
Console.Writeline("Please write a number between 1 and 6");
break;
}
Your other if statement was also kind of redundant because you already have other variable (dicecheck) with the value, so remove it.
private const int maxDiceValue = 6;
private const int minDiceValue = 1;
Console.Write("What number do you want the roll to be set to? (1-6)");
string diceString = Console.ReadLine();
int diceCheck;
if (!int.TryParse(diceString, out diceCheck) ||
diceCheck < minDiceValue ||
diceCheck > maxDiceValue) {
Console.WriteLine("Please enter a number between 1-6.");
return;
}
// add diceCheck to array here
Lets imagine the user introduce -1.
In the first condition you are validating if -1 >= 1 which is false, but you are also validating if -1 <= 6 which is true.
Instead of && (AND ALSO) you are using || (Or Else).
Since one of the condition is always true, the validating will always return true and therefore the code will run throwing an error.

Is this possible somehow in C# : if (a==b==c==d) {...}

Is there a quick way to compare equality of more than one values in C#?
something like:
if (5==6==2==2){
//do something
}
Thanks
if (a == b && b == c && c == d) {
// do something
}
In C#, an equality operator (==) evaluates to a bool so 5 == 6 evaluates to false.
The comparison 5 == 6 == 2 == 2 would translate to
(((5 == 6) == 2) == 2)
which evaluates to
((false == 2) == 2)
which would try to compare a boolwith an int. Only if you would compare boolean values this way would the syntax be valid, but probably not do what you want.
The way to do multiple comparison is what #Joachim Sauer suggested:
a == b && b == c && c == d
public static class Common {
public static bool AllAreEqual<T>(params T[] args)
{
if (args != null && args.Length > 1)
{
for (int i = 1; i < args.Length; i++)
{
if (args[i] != args[i - 1]) return false;
}
}
return true;
}
}
...
if (Common.AllAreEqual<int>(a, b, c, d, e, f, g))
This could help :)
No this is not possible, you have to split it into separate statements.
if(x == y && x == z) // now y == z
{
}
Good luck

Categories

Resources