How do I make an if statement repeat? - c#

I'm trying to make a title section for a start button, but I exit the program every single time.
string start1 = Convert.ToString(Console.ReadLine());
if(start1 != "1") {
Console.WriteLine("Not correct input please retry");
}
I haven't tried anything because I couldn't think of anything and looking up answer resulted in something that was way to out of my league. Please tell me if I didn't give enough information or not enough code.

Related

C#: If-Else Troubles

I have an issue with my if else statement to where it will only display the else output and not the if output.
default:
if (GradeVar >= 10) {
Console.WriteLine("That grade is a perfect score. Well done!");
} else {
Console.WriteLine("That grade is not passing.");
}
break;
Here's the specific code I am talking about; its for a program to display certain messages for grades.
The Simple Answer
GradeVar is always less than or equal to 9.
However, we need a minimal, but complete and verifiable example in order to truly understand what is going wrong. So far we can tell that you're most likely in a switch structure, and probably inside either a method or a loop in which GradeVar is a parameter, local variable, or property. It would be a good idea to revise your question and include the following:
Where GradeVar is declared.
Anywhere GradeVar's value is modified, prior to the location in code you've already supplied.
Any additional parameters, local variables, or properties that assist in the modification of GradeVar.
Anything else we may need to reproduce the issue at hand.
I hope this helps you get the answer you need, and wish you the best of luck in your endeavors.

Compare two textbox in c#

How can I compare two textboxes in c# using greater than or less than. Im working on billing system. I want the cash shoould be bigger than the total. if not. it will pop up messagebox for error. I already try convert to int. to double. to string.
Here's my current code right now.
if (txtCash.TextLength < txtTotal.TextLength){
MessageBox.Show("Cash must me bigger than the total");
txtCash.Focus();
return;
}
Any one can help me how?
I know text length is wrong. but im just using it.
I'm working on billing system. I want the cash should be bigger than
the total. if not. it will pop up message box for error.
You might be looking for something like this:
if (double.Parse(txtCash.TextLength) <= double.Parse(txtTotal.TextLength))
{
MessageBox.Show("Cash must me bigger than the total");
txtCash.Focus();
return; // i dont know why you put this here but i'll leave it there anyway.
}
else
{
var amount = double.Parse(txtCash.TextLength);
// DO something
}
You may want to further validate the user input if you wish. Example, if the user doesn't enter numbers...
Better ways to achieve your task in the most robust way possible, you should consider the below links:
How do I make a textbox that only accepts numbers?
double.TryParse(...)
Update:
Seems, you're not sure about the keyword var. I suggest you have a deep read of the MSDN reference page for var.

C# - Passively checking for key press

I am not using windows forms so this is not a duplicate of Capture keystroke without focus in console. Please remove the duplicate label or direct me somewhere else
So have been away from C# for a long time and trying to get back into it. I am messing with a small console app that requires inputting text from the user. The whole program works fine but now I want to add a check to see if escape is ever pressed.
I originally used ReadKey, but that just checks the current key which has two problems.
1. it uses the key pressed, so strings are missing a character (the one which was checked)
2. it is only in the moment. I want it to be passively waiting until its pressed
What would be the best way to do this?
ex:
I type the string "Hello World!"
If I press the desired key(lets say escape) at any time, I want it to react. Otherwise the string should be entered like normal
edit
example of made up dictionary program (yes, I know there is already a class for this)
while (Console.ReadKey().Key != ConsoleKey.Escape)
{
string entry = Console.ReadLine();
if (!entry.Contains(","))
{
...
}
else
{
...
}
}
Thank you all very much for your time.
Not sure what you're getting at but you can use this to detect if the Escape key was pressed.
if (Console.KeyAvailable)
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
// Do something
}
}
Or alternatively use a loop that breaks when Escape is entered:
var x = Console.ReadKey();
while (x.Key.ToString() != "Escape")
x = Console.ReadKey();

C# Filtering out "Space" key in UserActivityHooks.cs

I am making my own "Wordpad" type of thing, and I have successfully done it the usual way with a textbox, but now I am trying it with using the "UserActivityHooks.cs" program inside of it. The problem that I am having is when they press the space bar, it prints: HiSpaceMom instead of: Hi Mom. Is there any way to filter it out? I've tried to use this:
UserActivityHook hook;
string log = string.Empty;
public Form1()
{
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
hook = new UserActivityHook();
hook.KeyUp += (s, e) =>
{
log += e.KeyData.ToString();
if (log == "Space")
{
log = " ";
}
textLogs.Text = log;
};
But this method only works when "Space" is alone, and not next to any other characters. Can anyone please help? The source code is here:
http://code.google.com/p/wikipedia-aloud-reader/source/browse/trunk/WikiReader/UserActivityHook.cs?r=4
Based on the code you've provided above, the reason this is happening is because you're checking the log for equality with "Space", not the e.KeyData object. Ergo, given that you're constantly building the log, the only way log == "Space" would ever be true is the first time, if the first character encountered is a space. Thereafter log == "Space" will never and can never be true. (Unless the user actually typed in the characters "Space", but that's not something you'd want to convert - further reason to change your design.)
Additionally, you're adding the KeyData string to your log before you even check it, so this won't work as is even if you fix your conditional.
Two points on things you can do to fix this:
Check whether e.KeyData.ToString() == Space, not log.
You're going to run into performance issues with your log string if you're building a long log. You should be using a StringBuilder instead, appending each character to it, and converting it to a string when it's time to use or write it. As it stands, you end up creating an entirely new string every time you add a character to it.
So a remedied version of this code might look something like the following:
// log is defined above as a StringBuilder
hook.KeyUp += (s, e) =>
{
if (e.KeyData.ToString() == "Space")
{
log.Append(" ");
}
else
{
log.Append(e.KeyData.ToString());
}
textLogs.Text = log.ToString();
};
One last thing - though this should allow your implementation to do what you'd intended it to, there's some pretty severe flaws in the way it seems like it'll work. What happens if the user wants to delete the word they just wrote, or wants to change the word they wrote 50 characters ago? As it stands, you've made what appears like a perfectly serviceable, if basic, keylogger, but I'm not sure how you're planning to allow the user to do anything but write a single, perfectly-spelled/-formatted string, after which they can't do any editing. (Also - what happens if they press Control, or Shift, or Alt? Are you handling that elsewhere?)

C#, Skipping Console.ReadLine(); Console.Read(); while in loop

If I run my code and insert correct value first time program works fine and does its job, but if I input wrong path and allow for loop to spin second time it skips path=Console.ReadLine(); but it does not skip j = (char)Console.Read(); same thing persist through out the remaining code.
do
{
Console.WriteLine("Insert path:");
path = Console.ReadLine();
temp1 = CheckPath(path); //checks if inserted value is legit
if (temp1 == false)
{
Console.WriteLine("\nDo you want to skip this step(by default directory will be set to Desktop)? Y/N ");
j = (char)Console.Read();
if (j.Equals('Y') || j.Equals('y'))
{
path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
temp1 = true;
}
}
//User inputs y/Y loop will end and exit with either path chosen by user or with desktop path
} while (!temp1);
path = Console.ReadLine(); is being skipped if user fails to insert correct path. Been looking for the solution since yesterday and I have failed to find identical problem on the web. Link to full code: Code.
The call isn't being skipped - the problem is that Console.Read() will only return after the user has hit return - although it will only consume the first character it reads. So suppose that (when prompted about skipping) the user enters:
Nfoo
and then hits return... the value of path in the next iteration will be foo.
The simplest fix is probably to convert your Console.Read() call into Console.ReadLine() and just handle the situation where the user types more than one character.
It's much more useful to use Console.ReadKey for that - it will read exactly one key, and will not require you to press enter.

Categories

Resources