How do you add something to an uninitialized variable? c# - c#

Im trying to make a cookie clicker style thing where every time you click something it adds 1 to a variable. Im trying to do int clicks = clicks + 1 but it says that it is use of an uninitialized variable. I tried to set int clicks = 0 but then it says that clicks is already defined in the scope. I tried to see if i could do something like if (clicks == null) but obviously it cant check it because it is not a variable. I have only used c# for like a day, can someone please help?
private void cookie_Click(object sender, EventArgs e)
{
int clicks = 0;
clicks = clicks + 1;
numClicks.Text = "" + clicks;
}
^ this is the code. i also realized when i click it, it resets itself to 0 and goes back to 1, so it cant go 1, 2, 3 etc. is there a way to set the variable when the form starts and then start to add on clicks? im so dumb

int clicks = clicks + 1;
Is indeed nonsensical. This is the code that is declaring and initializing clicks, so it makes perfect sense that we can't ask "what is the value of clicks?" (in order so we can add one to it); until we have definitely assigned a value to clicks, the value is undefined.
Instead:
int clicks = 0;
And then when you want to increment it:
clicks++;

You'll want to do something like this:
int clicks = 0;//Define an integer 'clicks' and set it to 0
//and in your click handler:
clicks = clicks + 1;//Increment your count.
Note:
Clicks is an integer, it can never be null. (look up c# primitives for more info)
Using int clicks = clicks + 1 doesn't make sense. At the right side of the equation, what's the value of clicks? It's not defined yet.

The problem with your implementation is that every time the function gets called the first thing it does is sets clicks to 0. You need to initialize it outside of the function to avoid this. If you initialize it in the class it will be set to 0 initially when the class is created then you can increase the value everytime the functions is called. Not sure exactly your use case but without more information I would recommend doing something like this.
class YourClass {
// initialize outside of the function that increases the counter
int clicks = 0;
// rest of the code in class
private void cookie_Click(object sender, EventArgs e)
{
clicks++;
// this would also work: clicks = clicks + 1;
numClicks.Text = "" + clicks;
}
}

Related

Windows Forms - Integer being reset upon form load

My issue is that an integer created in my main class,
public int loadCountGold = 0;
that is incremented to when a button triggering the appearance of another form
public void goldButton_Click(object sender, EventArgs e)
{
loadCountGold += 5;
Console.WriteLine(loadCountGold);
GoldForm gForm = new GoldForm();
gForm.Show();
}
Is not having its incremented value carried over to the form where it needs to be used in an if statement.
private void GoldForm_Load(object sender, EventArgs e)
{
//Sets the random (within reason) value for gold
if (main.loadCountGold <= 1)//if its the firstload of the form
{
Console.WriteLine(main.loadCountGold);
Random rand = new Random();
currentGoldValue = rand.Next(1200, 1350);
}
}
I had included a few write lines at points before the form is opened, and one within the problem form to see what was happening to the value. This can be seen below
It shows the output that my program is giving, highlighted are the outputs from my "Main" class and the other are the ones being produced from the problem form.
The aim is to have the value incremented each time the form is opened so that the code within the if statement is only run the first time the form is opened, but currently it is running every time. (I am aware I would need to change the amount it is incremented)
In your main form, call GoldForm like this:
GoldForm gForm = new GoldForm(this);
In the constructor of GoldForm, do it like this:
Main main;
public GoldForm(Main main)
{
InitializeComponent();
this.main = main;
}
Now you don't create a new instance of Main every time you click the button.
Output after 3 button clicks:
5
10
15
This is an issue of needing a static variable rather than one instanced with the class. The easy answer is to change your integer declaration to:
public static int loadCountGold = 0;
now all references to this variable will point to the same thing.
I should specify that your reference in the later form needs to be Main with a capital M.
if (Main.loadCountGold <= 1)//if its the firstload of the form

Storing loop values from click button?

I am currently using a loop to create a new User Control on my windows form. I want it to add a single instance of this User Control in a new position where Y is incremented by 125 each time.
I'm pretty new with C# and Visual Studio, so with the below code, the first instance is being replicated each time I press the 'add' event. I was just wondering if someone can give some assistance on the best way to store the value of 'y' from this first instance to be passed into the loop the second time? Or if there is any better way to do this.
Thanks in advance!
private void btnAddRow_Click(object sender, EventArgs e)
{
int y = 175;
for (int i = 0; i <= 0; i++)
{
NewSkillRow nSkill = new NewSkillRow();
nSkill.Location = new Point(75, y += 125);
Controls.Add(nSkill);
btnAddRow.Click += new EventHandler(btnAddRow_Click);
}
}
Make your y variable local to the class (you can also initialize it with its default):
private int y = 175;
The event handler is called every time you click the button. So remove the initialization of y from there.
private void btnAddRow_Click(object sender, EventArgs e)
{
var nSkill = new NewSkillRow();
nSkill.Location = new Point(75, y += 125);
Controls.Add(nSkill);
}
Note that the event handler attachment was removed. Reattaching an event handler from within the handler would lead to an increasing number of invokations every time the button is clicked.
The loop is fine, but not necessary: For just one iteration, you can as well just omit it.
The use of the y += 125 is also ok, it relies on the specification that the return value of an assignment operator is the value that has been assigned.

How can I increase one of two numbers in a comparative statement with a button click

I'm making a little UWP app in C# that simulates drawing straws. The problem that I'm having is that I want the user to get to a point where they click a button, and the variable baseNumber (initially set to 2 -- the fewest amount of drawn straws to make any sense) is compared to a randomly generated number that is passed through from another button event. I have this part down.
The part that is giving me fits is that I want the next user to then click the same button, and I want the baseNumber incremented by 1, and have that new number compared to the losingStraw. If that user is declared safe, I want the number to increment again for the next user with their button click, until ultimately the numbers equal each other, a user draws the short straw, and another code path is taken.
I'm very new to coding, so what I want might not even be possible. Here's an example of what I've tried, below. I have also tried variants on a do / do while and a for loop.
If I could somehow stop something like a for loop at each pass and make it wait for user input (the button press), that would be ideal. I couldn't figure that out either though.
Any help or ideas you can offer would be greatly appreciated!
private void drawButton_Click(object sender, RoutedEventArgs e)
{
int baseNumber = 2;
int losingStraw = Convert.ToInt32(drawButton.Tag);
if (baseNumber < losingStraw)
{
instructions.Text = "You are safe!";
baseNumber = baseNumber++; // that doesn't work at all. I was hoping that baseNumber
}
else
{
instructions.Text = "You have drawn the losing straw";
}
}
You have to write baseNumber++; instead of baseNumber = baseNumber++; since ++ aka the unary operators helps increases integer value by one. Thus baseNumber++; means baseNumber = baseNumber + 1;
Edit
In your case the variable int baseNumber = 2; has been declare and initialized in the event itself thus every-time the event is fired the baseNumber will be initialized by 2 and you would not be able to see any changes. Thus you can do something like this
int baseNumber; // you can do 2 here as well
public YourFormName()
{
baseNumber = 2;
}
private void drawButton_Click(object sender, RoutedEventArgs e)
{
int losingStraw = Convert.ToInt32(drawButton.Tag);
if (baseNumber < losingStraw)
{
instructions.Text = "You are safe!";
baseNumber = baseNumber++; // that doesn't work at all. I was hoping that baseNumber
}
else
{
instructions.Text = "You have drawn the losing straw";
}
}
Just put the baseNumber outside the method, can be globally declared so that everytime you increment it, it will never to reset to 2 again when entered on butotn click :) -HAPPY CODING-
public class YourClass
{
int baseNumber = 2;
private void drawButton_Click(object sender, RoutedEventArgs e)
{
int losingStraw = Convert.ToInt32(drawButton.Tag);
if (baseNumber < losingStraw)
{
instructions.Text = "You are safe!";
baseNumber = baseNumber++; // that doesn't work at all. I was hoping that baseNumber
}
else
{
instructions.Text = "You have drawn the losing straw";
}
}
}

Make only 1 instance of a character allowed to be entered C#

I would like to allow only one instance of a character to appear in sequence in a textbox. In other words, I would like to prevent the user from entering sequential duplicate characters in my textbox. For example, if I were to make a calculator program, I would like to prevent the user from entering (( by accident instead of (.
You can detect the textbox's keydown event. And in the event, you check the last and second last character to see if it's the same. If it's the same, you can just remove the last character of the string.
But keep in mind that the above method has problem when your user pastes the entire string to the textbox.
The function will look the same for any textbox-like object, but of course the event to attach to will differ. Assuming Winforms TextBox, you will attach to the TextChanged event (i.e. mytextbox.TextChanged = mytextbox_TextChanged), and the function will look similar to the one below:
private void mytextbox_TextChanged(object sender, EventArgs e)
{
if (mytextbox.Text.Length < 2) { return; }
var stringToCheck = mytextbox.Text;
for (var i = 1; i <= stringToCheck.Length-1; i += 1)
{
if (stringToCheck[i].Equals(stringToCheck[i-1])
{
mytextbox.Text = stringToCheck.Remove(i, 1);
// Next two lines put cursor at end of textbox instead of beginning
mytextbox.SelectionStart = mytextbox.Text.Length;
mytextbox.SelectionLength = 0;
}
}
}

Addition using a single TextBox

I am writing a c# windowsform application for addition of two entries in a single text box.
I have 1 text box, 1 add button and 1 result button.
I need to achieve following algo,
User enter the no in text box. It will be stored in int n1.
User will press add button. At this time the content of the textbox.text will be get cleared and user must be able to enter the secound value in it.
This secound value will get stored in int n2.
Now when user click on result button he should get int result=n1+n2
I have written following in add buttons's click event,
n1=convert.Int32(textbox1.text);
textbox1.text="";
n2=convert.Int32(textbox1.text);//exception occures here
And result button's click event has,
textbox1.text=result.tostring();
I leanred the working of this program and find out that it is due to NULL value assignment to int n2.
I am bit confused how can I achieve above problem using single textbox?
Is there any way to provide the textbox.txt value through user through textbox field only?
Is there any property of textbox which I need to set?
I am very new to .net! Please help!
Thanks in advance for your kind attention!
move n2 = Convert.Int32(textbox1.Text); to your result button's click event
Add button click event:
n1=convert.Int32(textbox1.text);
textbox1.text="";
result button's click event:
n2=convert.Int32(textbox1.text);
result=n1+n2;
textbox1.text=result.tostring();
try something like this:
private int result=0;
addMethod()
{
//here you can use also int.TryParse
if(string.isnullorempty(textbox1.text.trim()))
textbox1.text="0";
result+=convert.toint32(textbox1.text);
textbox1.text=string.empty;
}
resultMethod()
{
textbox1.text=result.tostring();
}
look at the folloing code
private int i = 0;
private int[] a = new int[2];
private void button1_Click(object sender, EventArgs e)
{
int b;
if(Int32.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
int sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
}
You code contains a couple of errors:
You are using Int32 Convert.ToInt32(String) which is bad, because will throw an exception if the user enters something that can't be cast to an Int32, you should use Boolean Int32.TryParse(String, out Int32) instead, and check if the conversion is successful.
You are calling n2 = Convert.ToInt32(textbox1.Text); right after you set textbox1.Text = ""; and this is also bad, because it won't wait for a user input, it will try to convert an empty string to an integer right away, which will yield an exception.
You can't know when the user has finished inserting his number, so you have to rely to something external to the TextBox to let you know you should perform the addition.
Try the following:
Place a TextBox.
Place a Button.
Initialize a "grandTotal" integer variable to zero.
When the user press the button, parse the content of the TextBox in a temporary "submittedValue" integer variable, then sum this temporary variable to your "grandTotal" variable, and display the resulting "grandTotal" variable value.
This way you'll be able to continuously perform the addition operation on the previous total.
Example
The global variable:
protected Int32 GrandTotal = 0;
The Button click event handler:
Int32 currentValue = 0;
if (Int32.TryParse(userValue.Text, out currentValue))
{
GrandTotal += currentValue;
MessageBox.Show(String.Format("The new total is: {0}", GrandTotal));
}
else
{
MessageBox.Show("Invalid value!");
}
I have no idea why you are doing it in this fashion.
Still you can do this as
Declare n1, n2 as int? at the form level
Then in your Add click event do it in this fashion
if (! n1.HasValue)
{
n1 = int.Parse(textBox1.Text);
}
n2 = int.Parse(textBox1.Text);
textBox1.Text = "";
if you are going to do this for lotz of number then use List<int?> myIntList = new List<int?>() and your add event would be
myIntList.Add(int.Parse(textBox1.Text));
textBox1.Text = "";
and the result is int? result = myIntList.Sum();

Categories