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]);
}
Answer from T McKeown on Stack Overflowarrays 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]);
}
}
}
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--) {
use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
java - Printing elements of array called top10 backwards - Stack Overflow
java - Printing number in an array backwards - Stack Overflow
How to Print an array backwards using java
You can make a decrementing for loop.
//Array with 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for (int i = nums.size() - 1; i >= 0; i--) {
System.out.println(nums.get(i));
} More on reddit.com java - I want to print my string array elements backwards? - Stack Overflow
Videos
Can't seem to find anything on google. I want to know how to make it print backwards without changing the order manually.
No need for libraries, plain Java will do
new StringBuilder("Bird").reverse().toString();
Maybe You can using Apache commons StringUtils
public static void t(String [] list) throws IOException
{
for (int i = 0; i <list.length; i++)
{
String element = list[i];
String reverseElement = StringUtils.reverse(element);
System.out.println(reverseElement);
}
}