Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
Answer from user142162 on Stack OverflowArrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
Videos
Try this:
// Substitute appropriate type.
ArrayList<...> a = new ArrayList<...>();
// Add elements to list.
// Generate an iterator. Start just after the last element.
ListIterator li = a.listIterator(a.size());
// Iterate in reverse.
while(li.hasPrevious()) {
System.out.println(li.previous());
}
Guava offers Lists#reverse(List) and ImmutableList#reverse(). As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.
Example
List reversed = ImmutableList.copyOf(myList).reverse();
In case it about traversing the array backwards you can do like this
public static void main(String args[])
{
int a[] = {0, 1, 2, 3};
for (int i=a.length -1 ; i>=0; i--)
{
System.out.println("a[i] = " + a[i]);
}
}
}
Output
a[i] = 3
a[i] = 2
a[i] = 1
a[i] = 0
Start from the length minus one and go back to zero
for (int i = a.length -1; a >= 0; i--)
{
System.out.println("a[i] = " + a[i]);
}
If you know the position you want to move to, you don't have to search for it, just move there.
if (board[newPosition] == '0') {
board[newPosition[ = xIndex;
board[oldPosition] = '0';
} else {
throw new IllegalArgumentException("Error cannot move X to new position");
}
Note: The character '0' is not the value 0 (Actually it is 48 in ASCII)
I think the code is a bit flawed. First, I don't think you need to iterate all the way to 0. You should only iterate until you hit newPosition.
Then the while loop doesn't make much sense. I think you were after an if.
Lastly, personally I wouldn't throw an IllegalArgumentException in this case (actually, you're throwing after the first iteration regardless, so that's another flaw). It's the state of the board that's problematic, not the arguments. I would maybe throw IllegalArgumentException if one of the arguments was negative etc.
public void move(int xIndex, int newPosition) {
int oldPosition = getXPosition(xIndex);
for(int i= oldPosition - 1; i >= newPosition; i--) {
if(board[i] == '0') {
board[oldPosition] = '0';
board[i] = xIndex;
oldPosition = i;
} else {
//throw some custom exception; we found the other X here.
}
}
}
One approach would be to reverse the whole list, but this would have O(n) performance with respect to its size. Note that the commonly-used Collections.reverse method actually reverses the original list in place, which may be an undesirable side-effect.
As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order.
For example:
Copypublic class Reversed<T> implements Iterable<T> {
private final List<T> original;
public Reversed(List<T> original) {
this.original = original;
}
public Iterator<T> iterator() {
final ListIterator<T> i = original.listIterator(original.size());
return new Iterator<T>() {
public boolean hasNext() { return i.hasPrevious(); }
public T next() { return i.previous(); }
public void remove() { i.remove(); }
};
}
public static <T> Reversed<T> reversed(List<T> original) {
return new Reversed<T>(original);
}
}
And you would use it like:
Copyimport static Reversed.reversed;
...
List<String> someStrings = getSomeStrings();
for (String s : reversed(someStrings)) {
doSomethingWith(s);
}
Update for Java 21
As per this answer, Java 21 includes an efficient List.reversed() method which does exactly what is requested.
For a list, you could use the Google Guava Library:
Copyfor (String item : Lists.reverse(stringList))
{
// ...
}
Note that Lists.reverse doesn't reverse the whole collection, or do anything like it - it just allows iteration and random access, in the reverse order. This is more efficient than reversing the collection first.
To reverse an arbitrary iterable, you'd have to read it all and then "replay" it backwards.
(If you're not already using it, I'd thoroughly recommend you have a look at the Guava. It's great stuff.)
arrays have no concept of negative indices, if you want to traverse from the last to first then you must START at the LAST index and move to the FIRST.
for(i =3; i>0; i--){
System.out.println(var[i - 1]);
}
You were starting with a negative index which does not exist in arrays. It's also good practice to use array.length instead of an explicit number in case you change the size of the array later on.
public class RevIntArray {
public static void main(String[] args) {
int var[] = new int[] {1,2,3};
for(int i = var.length - 1; i >= 0 ; i--) {
System.out.println(var[i]);
}
}
}
Avoid indexes altogether? How about:
for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) {
final Object listElement = iterator.previous();
}
Start the iteration at list.size() - 1 because array (or ArrayList) elements are numbered from 0 up through 1 less than the size of the list. This is a fairly standard idiom:
for (int j = list.size() - 1; j >= 0; j--) {
// whatever
}
Note that your forward iteration works because it stops before reaching list.size().