Variables not adding correctly

Hello. I declared a variable in AppLab to hold the value of how many times a checkbox has been clicked. However, instead of adding 1 to the value, I am getting N as the output. When I was getting 1 for the output, it wouldn’t go beyond 1. Adding some additional steps to the checkbox.clicked code gives me the N output, though.

The code I did would work in AppInventor or many other programming languages. But, it seems like App Lab doesn’t respond the same way to the code. Any thoughts would be greatly appreciated. The code is below. Thanks.

onEvent(“button1”, “click”, function( ) {
setScreen(“screen2”);
});
onEvent(“checkbox1”, “click”, function( ) {
var Nike;
var Nike = Nike + 1;
setText(“label5”, Nike);
if (Nike >= 1) {
setText(“label7”, “Enjoy the Nikes”);
} else {
setText(“label7”, “No Nikes?”);
}
});
onEvent(“dropdown2”, “change”, function( ) {
var dropdown_Value = getProperty(“dropdown2”, “value”);
setScreen(dropdown_Value);
});

@saundersj,

Again, on this, I may suggest you post your question in the CS Principles forum as it goes beyond the scope of how CS Discoveries uses App Lab, but a few observations. Each time the checkbox is clicked, you are declaring the variable Nike twice. I’m not an App Lab expert, but it seems like you should only declare the variable once and the 2nd time only update it (without starting with the “var” keyword). I’m also not sure that you should be declaring it only after the button is clicked as that makes it a local variable within that function (that is reinitialized each time the checkbox is checked).

Hope this helps you debug a little, but if you still have questions, try posting in the CSP forum and I’m guessing you’ll get some help over there!

thanks!

Mike

@saundersj,

Update. I remixed your code and declared the variable outside the function and then updated it inside the function and after that it started working.

Give it a shot! Good luck!

Mike

I had tried putting the variable at the top but still get the same result. I get N for the output instead of the number 1. It’s very strange as the code is so basic. I’m declaring a variable and then just adding 1 to it in the checkbox event. But, instead of just adding 1, I’m getting the letter N for the output.

var Nike = 0;
onEvent(“button1”, “click”, function( ) {
setScreen(“screen2”);
});
onEvent(“checkbox1”, “click”, function( ) {
var Nike = Nike + 1;
setText(“label5”, Nike);
if (Nike >= 1) {
setText(“label7”, “Enjoy the Nikes”);
} else {
setText(“label7”, “No Nikes?”);
}
});
onEvent(“dropdown2”, “change”, function( ) {
var dropdown_Value = getProperty(“dropdown2”, “value”);
setScreen(dropdown_Value);
});

In your example, you are declaring Nike twice. When you are adding one to Nike, you are just updating the variable so remove the var. See if that helps.

FYI - you may rethink the else statement. It doesn’t trigger since the event only kicks-in when Nike’s value is 1 or more.

Michelle

2 Likes