if(string s; s = Console.ReadLine(); s == "ja" || "Ja")
A screenshot of all the errors i got from that single line
I dont understand a single of them
Can somebody explain
You cannot declare a variable inside of if statement, and this is also invalid: s == "ja" || "Ja" you need to separate each condition like this:
string s = Console.ReadLine();
if(s == "ja" || s == "Ja")
Or you can just use:
if(s.ToLower() == "ja")
string s;
s = Console.ReadLine();
if(s == "ja" || s== "Ja")
{
}
?
This is not a valid C# syntax. Inside if statement there should be an evaluation that results in a boolean value. Can't declare new variables inside, nor s == "ja" || "Ja" makes any sense.
C# does not allow that sort of thing. Try something like the following:
string s = Console.ReadLine() ;
bool isEndOfFile = s == null ; // Console.ReadLine() returns null at end-of-file
if ( isEndOfFile ) throw new Exception( "That was unexpected!" ) ;
bool isYes = !isEndOfFile && s.Trim().Equals( "Ja" , StringComparison.CurrentCultureIgnoreCase ) ;
if ( isYes )
{
HandleYesInput() ;
}
In general, keep things simple. Intentional programming will help you: work in a declarative manner to express your intent using small discrete methods and local variables as flags for each of the conditions you're testing, rather than trying to do everything in one complicated expression. You could do something like this:
string s = null ;
if ( (s=Console.ReadLine()) && s != null && s.Trim().Equals("Ja",StringComparison.CurrentCulture.IgnoreCase) )
{
...
}
You gain a little brevity at the expense of readability, traceability and debugability. When your code doesn't work as expected, which version do you think will be easier to understand or to diagnose and fix? That goes triple, if the person who's assigned the task of fixing the problem doesn't understand the code or what it's trying to accomplish and has to get up to speed quickly.
And that person might well be you, looking at code your wrote 5 years earlier.
Related
I worked on an edabit challenge for hours and finally, I resolved this challenge by error.
Here's what didn’t work:
/*****************************/
public static bool IsStrangePair(string str1, string str2)
{
char firstCharInStr1 = str1[0];
char lasttCharInStr1 = str1[str1.Length-1];
char firstCharInStr2 = str2[0];
char lasttCharInStr2= str2[str2.Length-1];
if (str1.Length == 0 && str2.Length == 0)
return true;
if (str1.Length == 0 || str2.Length == 0)
return false;
return firstCharInStr1 == lasttCharInStr2 && lasttCharInStr1 == firstCharInStr2;
}
So I add IsNull at the beginning and it worked :S - why?
public static bool IsStrangePair(string str1, string str2)
{
// A What I add after
if(string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2))
{
return str1 == str2;
}
char firstCharInStr1 = str1[0];
char lasttCharInStr1 = str1[str1.Length-1];
char firstCharInStr2 = str2[0];
char lasttCharInStr2= str2[str2.Length-1];
// B-----My first idea
if (str1.Length == 0 && str2.Length == 0)
return true;
if (str1.Length == 0 || str2.Length == 0)
return false;
return firstCharInStr1 == lasttCharInStr2 && lasttCharInStr1 == firstCharInStr2 ;
I didn't understood why it was validate because I was under the impression that my A "IsNullOrEmpty solution" was the repetition of my First Idea so it was insane (for me).
So I understood(i think) that I had to choose between A or B and that the key is to declare my variable AFTER my B or my A ( I have too choose B OR A)
So I'm confused cause I was thinking that we had to declare variables before to start/or use it. Why It doest work when my variables are declared First?
I wish I'm clear
Null can be confusing when first starting up.
Null is not an actual value but rather an empty pointer (if you are familiar with pointers). This means that you have declared a name but you have not actually pointed to any value.
Think of it as you have declare that you want a house of type mansion, but did not declare an address. It is impossible to open maindoor on, but you can check if the address is absent.
You can check for null, you can even in some cases use it to your benefit, however in your case you are trying to take the [0] in a thing that does not exist (is null).
And therefor you have the wonderful option to use string.IsNullOrEmpty(stringToBeTested);
In dot.net 6 you will find green squickly lines everywhere a variables risks being null.
The code asks the user whether he/she has eaten something or not. Then it loops the question until a valid input (such as "nothing" or "something") is entered. My problem is that when I use the "||" operator, the loop continues no matter what is inputted. To my understanding, the loop should end when the user inputted string is equal to "nothing", "something", or both based on the operator I'm using. But this result only occurs when I use the "&&" operator, which confuses me as that would mean that the user would have to input a string value equal to "nothing" AND "something". So my question is why does my loop work with the "&&" operator but not "||" or "^" operator ? Thanks in advance.
struct multivar
{
public int userInt;
public string userText;
}
class Program
{
static void Main(string[] args)
{
multivar structHolder;
string shrinkRay = "";
while ((shrinkRay != "nothing") || (shrinkRay != "something"))
{
Console.WriteLine("What did you eat today?\n1)Nothing?\n2)Something?");
structHolder.userText = Console.ReadLine();
shrinkRay = structHolder.userText.ToLower();
if ((shrinkRay != "nothing") || (shrinkRay != "something"))
{
Console.WriteLine("Please input a valid response such as \"Nothing\" or \"Something\".");
}
}
your logic:
str != 1 || str != 2
can be rewritten as
!(str == 1 && str == 2)
its obvious one of the inner statements must be false, so the whole inner statement will be false. The negation will make the statement true, always. You need to alter your logic as others have said.
The user cannot enter both "nothing" and "something" so, your || is always going to be true. It simply is the correct logic to use &&.
Is either
(shrinkRay != "nothing" && shrinkRay != "something")
Or
!(shrinkRay == "nothing" || shrinkRay == "something")
See De Morgan's laws
I have a function that calls a lot of other functions from different objects. Each function has to return true before calling the next one. As you can see I am using too many if statements. How can I improve the code and make it neater? Thanks
bool ISOKToDoSomthing()
{
boo retVal = false;
retVal = ObjA.CheckVersion(oldVersion);
if(retVal)
{
retVal = objB.CheckUserRight();
}
if(retVal)
{
retVal = ObjC.ISDBExist();
}
if(retVal)
{
retVal = OjbD.ISServerUp(ServerName);
}
//tons of similar code as above
.........
return retVal;
}
return
ObjA.CheckVersion(oldVersion) &&
objB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName);
My advice: do nothing to this code without a clear business case for making the change.
Your code is clear, obvious, likely correct, easy to maintain and easy to debug. Why on earth would you want to change it in any way? Spend your time adding value by fixing bugs and adding features, not by changing working code unnecessarily. When your boss asks you "so what did you do today?" the answer should not be "I increased our schedule risk to by making unnecessary cosmetic changes to correct, working, already-debugged code".
Now, if there really is a problem here, the problem is likely not that the code is hard to read, but rather that the code rigidly encodes what ought to be a user-configurable business process. In that case, create an object called "Workflow" that encodes the business process, and an engine which evaluates an arbitrary workflow. Then construct an instance of that object that represents the desired workflow based on input from the user.
That actually adds value for the user; the user cares not a bit whether you use nested "if" statements or not.
if (!ObjA.CheckVersion(oldVersion)) return false;
if (!ObjB.CheckUserRight()) return false;
if (!ObjC.IsDBExist()) return false;
if (!ObjD.IsServerUp(serverName)) return false;
... your other checks ...
return true;
The short-circuiting of && is useful for a few conditions, but if you have "tons" of them, IMO that's way too much to try and stick in one statement.
A combination of the two might be useful, though. More useful still would be to condense some of these checks together into bigger chunks (but smaller than IsOKToDoSomething). For instance, check whether you have access to the database (whether it exists, whether you can log in to it, etc) all at once
Truth be told, the fact that you have so many objects to check hints at a design issue -- namely, you're trying to do too much at once, or you have a "god object" somewhere that has its little tentacles in every aspect of the system. You might want to look at fixing that.
return ObjA.CheckVersion(oldVersion) && objB.CheckUserRight() && ObjC.ISDBExist() && OjbD.ISServerUp(ServerName)
The && operator will short-circuit, so you can chain them like so:
bool ISOKToDoSomthing()
{
return
ObjA.CheckVersion(string oldVersion) &&
objB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName) &&
//tons of similar code as above
.........
}
bool ISOKToDoSomthing()
{
return ObjA.CheckVersion(string oldVersion) &&
ObjB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName);
}
Perhaps?
retVal = objB.CheckUserRight() && ObjC.ISDBExist() && OjbD.ISServerUp(ServerName);
etc.
A side note, you can test for example, if objB is null before calling a method on it in one statement (the code will break execution as soon as a condition has not been met, i.e. won't call the next condition) so you don't need lots of if(objB != null) type statements. E.g.:
retVal = (objB != null && objB.CheckUserRight()) && (ObjC != null && ObjC.ISDBExist()) && (OjbD != null && OjbD.ISServerUp(ServerName));
You can leverage the fact that C# does short-circuit evaluation:
return
ObjA.CheckVersion(oldVersion) &&
objB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName);
Editing to fix syntax on CheckVersion's parameters
How about using and:
retVal = ObjA.CheckVersion(oldVersion) &&
objB.CheckUserRight() &&
ObjC.ISDBExist() &&
OjbD.ISServerUp(ServerName);
return retval;
To make the code less wordy, you could try a while loop. Given that your method here is to not ever change the value of your original value if it /ever/ turns false, then it would be while(retval) {} and iterate over a list of actions. Personally, I think this is ugly. Consider using a switch, or even (yuck on this, but it would work) a bitwise enum.
From my perspective, when I see myself writing code like this, I've made a grave architectural mistake somewhere and I should really rethink the reason behind making this call. Perhaps you should take another look at your logic, rather than just your code. Sit down and draw some boxes and work a bit more in the design phase and you might find yourself building things very differently.
edit: or yeah, like everyone else did, you can make your iteration a single if statement. Again, this is a bigger problem than a long list of booleans.
It depends on how much you want to change. Perhaps instead of returning a bool from your sub-methods, you could throw an exception.
bool retVal = true;
try
{
ObjA.CheckVersion(oldVersion);
objB.CheckUserRight();
ObjC.ISDBExist();
OjbD.ISServerUp(ServerName);
}
catch (SomeException ex)
{
// Log ex here.
retVal = false;
}
return retVal;
If you do something like this, IsDBExist probably isn't the best name (since Is generally translates to "returns a bool" in my mind), but you get the picture.
I was using the following:
!string.IsNullOrEmpty(Model.ProductID)
But now I need to also check that the string is not equal to "0000". What's the most easy way to do this check?
!string.IsNullOrEmpty(Model.ProductID) && Model.ProductID != "0000"
or write an extension method:
public static class StringExtensions
{
public static bool IsNullEmptyOrZeros(this string value)
{
return !string.IsNullOrEmpty(value) && value != "0000";
}
}
and then:
if (!Model.ProductID.IsNullEmptyOrZeros())
{
...
}
if(!string.isNullOrEmpty(Model.ProductID) && Model.ProductID != "0000")
How about...
if (!string.IsNullOrEmpty(Model.ProductID) && Model.ProductID.Trim() != "0000")
I really don't think there's a function for your specific case. It's not very often that people want to check a string for all of those three conditions.
And there's no particular reason to worry about "optimizing" this code anyway. The && operator is short-circuiting, meaning that the string comparison won't even happen unless the string does contain some value.
In addition to the IsNullOrEmpty check, add a test for string.Trim('0').Length != 0. This will also catch strings that are any number of zeroes (instead of specifically 4).
I think you also need to check if the value is " "
If in C#4.0 , you should use the
!string.IsNullOrWhiteSpace(Model.ProductID) && Model.ProductID != "0000"
Or not ,
!string.IsNullOrEmpty(value) && value.trim().length > 0 && Model.ProductID != "0000"
I am still pretty new to C# and am having a difficult time getting used to it compared to C/CPP.
How do you exit a function on C# without exiting the program like this function would?
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
System.Environment.Exit(0);
This will not allow return types and if left alone it will keep going on through the function unstopped. Which is undesirable.
There are two ways to exit a method early (without quitting the program):
Use the return keyword.
Throw an exception.
Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.
If your method returns void then you can write return without a value:
return;
Specifically about your code:
There is no need to write the same test three times. All those conditions are equivalent.
You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:
if (textBox1.Text == String.Empty)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
}
return; // Are you sure you want the return to be here??
If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.
You might want to use Environment.Newline instead of "\r\n".
You might want to consider another way to display invalid input other than writing messages to a text box.
In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
will always return at that point. However:
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
}
will only return if it goes into that if statement.
I would use return null; to indicate that there is no data to be returned
The basic problem here is that you are mistaking System.Environment.Exit for return.
#John, Earlz and Nathan. The way I learned it at uni is: functions return values, methods don't. In some languages the syntax is/was actually different. Example (no specific language):
Method SetY(int y) ...
Function CalculateY(int x) As Integer ...
Most languages now use the same syntax for both versions, using void as a return type to say there actually isn't a return type. I assume it's because the syntax is more consistent and easier to change from method to function, and vice versa.
If the function is a void, ending the function will return. Otherwise, you need to do an explicit return someValue. As Mark mentioned, you can also throw an exception.