programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Array Question.

David Laverdy
Greenhorn
Posts: 18
Im writing a method to rotate the numbers in a array given a specified number.

What I'm finding is the loop works once, than after that the loop seems to fail, and I can't figure out why. It's failing in the way that the temp variable is assigned correctly the first 2 times the loop is initiated, than the temp variable stays the same. I hope this is enough information to nudge me along. Thanks for all the help in advance!

Ulf Dittmer
Rancher
Posts: 42972
73
Sevral points in no particular order:

- You're rotating the first "numberOfPositions+1" elements, not the first "numberOfPositions" elements; is that what you want to do?

- Assuming that the first element should go into the (numberOfPositions+1)-th spot, line 9 is incorrect. Not sure what "nElems" is, but you probably meant to use "numberOfPositions" instead.

- you should move the assignment of the "temp" variable out of the loop - it gets assigned the value of the 0-th element, but should not change afterwards. (At least if I understand the intent of this code correctly.)

Steve Luke
Bartender
Posts: 4181
22
The logic in your program has some flaws. The best way to see how it works is to take a pencil and paper and draw it out. For example, assuming a[] is [1,2,3,4,5], and the nElems variable has the array length (5), the first loop would look like this:

The number in parenthesis is the value of the variable after assignment. So after line 3 is executed, temp has a value of 1. If you do this, you should see how the flow goes, and why you get the behavior you do. I would then do the reverse to fix the problem: draw the sequence that does what you want to happen using pencil and paper. Then translate that sequence into code.