0

I'm working on a program to learn how to use arrays in my computer course and my display button doesn't work properly after the first press. The first time I click it, it works properly and displays everything but the 2nd time it stop showing the first value and starts showing the last value twice, the 3rd time cuts off the 2nd value and displays the last value three times and so on. And when I press the button to find the sum of all values it gives me the sum of all of the values that will show up after I hit the display button. Here's my code, and sorry about the french commentary, it's for school.

function afficherFunction(event:MouseEvent):void 
{

  // Compose cette fonction visant à afficher tous les éléments du tableau.
  txtSortie.text = "";
  var entier:int;
  entier = -1
  for (var i:int=entier; i < mesEntiers.length; i++)
    {
        if (i+1 < mesEntiers.length)
        {
        mesEntiers[i] = mesEntiers[i+1];
        affichage = affichage + mesEntiers[i] + "\n"
        }
    }
  txtSortie.text = affichage;
  affichage = "";
  i = -1;
} //Fin fonction afficher.
1
  • The code works as it should. Values in the end are duplicated because they are copied from the last value. Next time they are copied again, etc. So at some step all values become copy of the last value. Commented Apr 1, 2015 at 19:28

1 Answer 1

1

mesEntiers[i] = mesEntiers[i+1];

This line is your problem. Not sure what you meant for that line to be doing, but it's setting the value at index i to the value at the next index--essentially shifting all the values down one (and losing the value at index 0).

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

5 Comments

I removed this line to try and fix it and instead of displaying "10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110" it displays "undefined, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100"
Because you're setting entier and thus i to -1. So the first time through the loop it tries to access array index -1, which is undefined. Start with index 0 if you want to loop through your array.
So i made it set entier to 0 but now it shows "10, 20, 30, 40, 50, 60, 70, 80, 90, 100" but it doesnt show my value of 110
I'm sorry, but I'm not going to continue to debug this for you. You might want to read up some more on Arrays, or ask your instructor to go over these concepts again in class. Good luck!
Alright, thanks. And I would ask the teacher but it's an online course and she just says to use the forums but I'm ahead in my course.

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.