1

The problem with this code is when I'm executing the if condition. The condition only works if i am using if (pixel.getx() <=100) but does not work for a var x = pixel.getX() & if (x <= 100). Can someone tell me why?

var image = new SimpleImage (200,200);
print (image);

for (var pixel of image.values())
var x = pixel.getX();
var y = pixel.getY()

if (x <= 100 && y <= 100)

{
pixel.setRed(255);
pixel.setBlue(0);
pixel.setGreen(0);  
}

else if (x > 100)
{
pixel.setBlue(255);
pixel.setGreen(0);
pixel.setRed(0);
}   
print (image);
3
  • 1
    What is SimpleImage? getx and getX are two different methods. Is that the issue? Or just a typo in the question? Commented Dec 2, 2016 at 1:19
  • 1
    Your for (var pixel of image.values()) loop isn't using { braces } and therefore operates only on the next statement after it, var x = pixel.getX(); The rest of your code, including the if statement, is not part of the loop. Commented Dec 2, 2016 at 1:23
  • 1
    var x = pixel.getX() & if (x <= 100) is not valid syntax, so that's an issue Commented Dec 2, 2016 at 1:25

2 Answers 2

2

your for loop is missing {}. all it does the way you have it in your example is executing var x = pixel.getX(); as many times as there are image.values()

if you need to repeat a multi line block of code within a for loop it needs to be inside {}

if you are repeating one statement - you don't need {} - that's why it worked when you had if (pixel.getX() <= 100) {...}

Sign up to request clarification or add additional context in comments.

Comments

2

Your for loop is missing the braces { } and that's why its not working.

Modified code,

var image = new SimpleImage (200,200);
print (image);

for (var pixel of image.values()) {
    var x = pixel.getX();
    var y = pixel.getY()

    if (x <= 100 && y <= 100) {
        pixel.setRed(255);
        pixel.setBlue(0);
        pixel.setGreen(0);  
    } else if (x > 100) {
        pixel.setBlue(255);
        pixel.setGreen(0);
        pixel.setRed(0);
    }   

    print (image);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.