infinite loop even when I switch off capslock - c#

I am trying break; out of frustration. Is there an event handler I need to know about in console?

You're only setting the value of capslock once, prior to entering the loop. bool is a value type, so you get a copy of the Console.CapsLock property, not a reference to it. Your variable is never going to change value after that first assignment. What you want is something like:
while(Console.CapsLock)
{
// inform user, perhaps remove the loop and just tell them once
}
Or
capslock = Console.CapsLock;
while(capslock)
{
Console.WriteLine("CapsLock on");
capslock = Console.CapsLock;
}
On a side note, writing a message as fast as possible in a loop is probably a bad idea since it's just going to fill up the screen before the user has a chance to do anythign about it.

Not to answer your original question but it appears the reason you are checking for caps lock is you want the username that is going to be typed in in all lowercase so you can do a users.Contains(username) or something similar below where you provided in the screenshot.
A better way to do it is use the contains overload that lets you set a comparer, then use a case insensitive string comparer to test.
if(users.contains(username, StringComparer.OrdinalIgnoreCase))
{
//username existed
}
else
{
//username did not exist
}
There are similar overloads for String.Equals that lets you ignore case too
//This would return true if "username = marietjie" and "testUsername = MARIETJIE"
if(username.Equals(testUsername, StringComparison.OrdinalIgnoreCase))
{
//username matched
}
else
{
//username did not match
}

The solution for this kind of problem!!

Related

How to check the order in which variables activate?

I'm trying to make a system to check in what order do variables activate in order to prevent certain bugs. I'm sorry if it sounds confusing.
Example:
I have the following Bools
bool firstCheck
bool secondCheck
bool thirdCheck
I want to check if the variables activate in the following order (from left to right):
firstCheck == true > secondCheck == true > thirdCheck == true > //Do code
For simplicity, suppose that when a variable is activated, the following checks continue, but the original variable changes its condition to false.
I also want to check if, say, once firstCheck is true and secondCheck is true, and proceeds to the next check(remember that they change back to false ), suddenly, the variable secondCheck is true, meaning that whatever the process was, it went "back". If that happens, I want to do some code.
I don't know if I explained it correctly if you have any doubts and would like to help, don't worry and ask them
It's probably best to address the first issue of terminology, variables don't get activated, a better way to describe what's happening is to describe them as set/assigned or initialized. Value types are set, nullable value types and reference types are initialized, both can be assigned.
Depending what you need, an enum can be mutually exclusive and have multiple values.
Example:
Given
public enum State
{
First,
Second,
Third,
Finished
}
Nonsensical state machine example
var state = State.First;
while (state != State.Finished)
{
switch (state)
{
case State.First:
Console.WriteLine($"You are state {state}. Type something");
Console.ReadLine();
state = State.Second;
break;
case State.Second:
Console.WriteLine($"You have progressed, State = {state}. Type something");
Console.ReadLine();
state = State.Third;
break;
case State.Third:
Console.WriteLine($"You are good at this, State = {state}. Type something else");
Console.ReadLine();
state = State.Finished;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
Console.WriteLine($"Game over, you can type stuff. State = {state}");
Output
You are state First. Type something
sgf
You have progressed, State = Second. Type something
fgh
You are good at this, State = Third. Type something else
fghfg
Game over, you can type stuff. State = Finished

How do I compare the elements in the array with the elements entered in the textbox sequentially in c#?

My goal is to actually make a guessing game, so I created two arrays with Mysql data called answers and questions. And what I want to do is take the value from the user and if it is true, for example my first answer 'fashion' matches the guess the user entered in the textbox, I want the label to write correct and continue with the next answer and try to find the next answer
My code returns true when I enter my values ​​in the array into the textbox, but I want them to be in order. How do you think I can use the for loop. How do you think I can use the for loop to make an ordered comparison?
for (int i=0;i<cevaplar.Count;i++)
{
string tahmin = textBox1.Text;
if(cevaplar.Contains(tahmin))
{
label1.Text = "true";
continue;
}
else
{
label1.Text = "false";
break;
}
}
}
In your code you use "cevaplar.Contains(tahmin)". With contains you're checking if tahim can be found anywhere in your array, without taking any order in account.
The solution to your problem should be quite simple. Just don't use contains in this situation but use a simple indexer to compare the elements. Try the following:
Replace:
if(cevaplar.Contains(tahmin))
{
...
}
With
if(cevaplar[i] == tahim) //here you check only if the i'th element is matching.
{
...
}
Good luck!

How to use value assigned within a for loop

I declare the variable setPassword outside of the loop and then give it a value within the loop. Then in the next do-while loop I try to use the value assigned but it says "Use of unassigned local variable".
profile[I] is an array of objects that are created prior to the loops. Is the value being assigned in the loop not saving or is the value of profile[I].Password null because the object hasn't been created yet?
bool good = false;
string username;
do
{
bool broke = false;
Console.WriteLine("Please create a username");
username = Console.ReadLine();
for (int i = 0; i < profile.Count; i++)
{
if (username == profile[i].Username)
{
Console.WriteLine("The username already exists");
broke = true;
break;
}
}
if (broke == false)
{
good = true;
}
} while (good == false);
Console.WriteLine("Please create a password");
string password = Console.ReadLine();
profile.Add(new Users(username, password, 0));
string setPassword;
bool validUser = false;
do
{
Console.Clear();
Console.WriteLine("Enter your username");
string tryUsername = Console.ReadLine();
for (int i = 0; i < profile.Count; i++)
{
if (profile[i].Username == tryUsername)
{
setPassword = profile[i].Password;
validUser = true;
}
}
if (validUser == false)
{
Console.WriteLine("Invalid username. Usernames are case sensitive");
Thread.Sleep(2500);
}
} while (validUser == false);
bool validPass = false;
do
{
Console.WriteLine("Enter your password");
string tryPass = Console.ReadLine();
if (tryPass == setPassword) //this is the error
{
validPass = true;
}
else
{
Console.WriteLine("Invalid password. Passwords are case sensitive");
}
} while (validPass == false);
The compiler can't know it will actually get assigned (and it doesn't if not all if statements you have evaluate to true).
Assign a default value and you will be fine:
string setPassword = null;
I initiate the variable setPassword outside of the loop and then give it a value within the loop.
This is the problem. The system cannot guarantee that a value is assigned before it is used.
It is possible that the loop iterates 0 times.
It is also possible that condition of the surrounding if statement evaluates to false.
Both of these situations lead to setPassword never getting a value.
So the compiler gives you an error, it is possible that you are using setPassword before it has a value.
The solution is to set it to a default value outside the loop, and outside the if.
This is because the compiler can´t know that your for-loop is executed at least once and in particular that the if-statement within the loop also passes at least for one iteration of that loop. Thus - at least from the perspective of the compiler - it is possible that setPassword is never assigned a value and thus you get that error.
Assign null at the start:
string setPassword = null;
Basically the problem is this :
You are using them in mostly the if statements, the if statements uses a variable. But you only declared but never defined the variable globally/locally, which automatically gives an error, despite the variable will be taking a user's input locally, the if statement is unfortunately too stupid to detect that for you, plus it also takes the possibility that the user skips the step of giving an input too. Hence, you need to set a default value.
Like what they stated, you can use :
string setPassword = null; or string setPassword = "";
[Don't need to mind nullables , strings can be null by default]
To solve your problem, you should assign setPassword to string.Empty, null, or some other value, based on your use case
If you are curious about -
Why does the compiler complain that the variable is unassigned even though you assigned a value to it in while loop?
This is called the Definite Assignment behavior of the C# language. A variable is considered to be definitely assigned if
The variable was initialized at the time of declare - either with a default value or an explicitly value
Otherwise, if the compiler can prove, by static flow analysis (in simple words, compile time checks), that all possible execution paths leading up to the first use of variable will assign a value to the variable. Note, the static flow analysis is the key here, the compiler does not evaluate or take for granted that any run-time possibilities (conditions in if, while, for etc. control statements) will eventually assign the variable a value.
See Definite assignment at MSDN for more info. It is an archived document but should still be good a reference.
Also DotNetPerls Page describes it in simple language.
Disclaimer: I have no association with DotNetPerls.

Saving settings based on strings

I need to save to a different setting based on the input string. Why will this line not work?
Properties.Settings.Default + colorOptionNametoSave = selectedIndexString;
Properties.Settings.Default.Save();
Where the colorOptionNametoSave is a different color setting and the selectedIndexString is the value to save. However I get the message:
Error 2: The left-hand side of an assignment must be a variable, property or indexer.
The only work around I can think of is a switch statement, but I have a lot of colors so that would be really long. Any ideas on a more efficient solution?
if/else or a switch is what you are looking for.
You cannot concatenate a variable name!
So a solution for you would be something like this ( if colorOptionNametoSave is a string ):
if(colorOptionNametoSave == "Blue")
{
Properties.Settings.Default.Blue = selectedIndexString;
}
else if(colorOptionNametoSave == "Red")
{
Properties.Settings.Default.Red = selectedIndexString;
}

can I use a c# switch here?

i would like to refactor this code. Maybe if possible by using a switch? Or is it the same in terms of performance?
string rawUrl = context.Request.RawUrl ?? string.Empty;
if (rawUrl.Contains("mypage.aspx"))
{
}
if (rawUrl.Contains("mypage2.aspx"))
{
}
etc..
Not directly, since you want a "contains" relation, rather than an exact equality.
However, if you so desire, you could do it indirectly by attempting to parse the page name out of what I assume would be the URL, storing it in a separate String variable, and switching on that String.
For example:
// Get the URL from some external source (wherever you're already getting it from)
String rawUrl = "http://www.example.com/foo/bar.aspx";
// Means of parsing will be dependent on the format in which you expect the URL.
String page = rawUrl.Substring(rawUrl.LastIndexOf("/") + 1);
switch (page) {
case "bar.aspx":
// Do stuff
break;
case "foo.aspx":
// Do stuff
break;
}
And, of course, please take this parsing methodology with a grain of salt; this example was to show you that it is possible, but note that this method of parsing could potentially throw an exception in a number of cases, but I've omitted those checks for the sake of brevity.
Switch Cases must be a constant value. You're best bet there is to use if/else like so:
string rawUrl = context.Request.RawUrl ?? string.Empty;
if (rawUrl.Contains("mypage.aspx"))
{
//code
}
else if (rawUrl.Contains("mypage2.aspx"))
{
//more code
}
If you're concerned about performance (which is good!) then the else is the way to go. While not using an else will have the same functionality, by adding the else, you're telling the code to not process any of the other if conditions. So 10 if statements will result in 10 if conditions being processed not matter what, while 10 if/else statements might result in 10, or it might only result in 1.
EDIT:
Thought about this some, and I noticed you were using the context object. If you really wanted a switch statement, you can do the following:
string page = context.Request.Url.Segments.Last();
switch(page)
{
case "mypage.aspx":
//code
break;
case "mypage2.aspx":
//more code
break;
}
Not for a contains.
Try to isolate page name alone and you can could do it.
switch(pageName)
{
case "mypage.aspx";
break;
case "mypage2.aspx";
break;
}
I think it is better to use a Dictionary.
First, extract the file name from the raw url.
Then, use a Dictionary<string,TValue>.
If the actions to the pages are almost the same, set TValue to the type of the data associated with the pages.
If the actions are very different, set TValue to a delegate type such as Action.

Categories

Resources