-1
public static void printBackwards(int[] list) {
if (list.length == 0) {
        System.out.println("");
} else {

    for (int i = list.length - 1; i >= 0; i--) {
            System.out.println("element" + (Arrays.toString(list))+"is " + list[i]);
    }
        System.out.println("");
}

how do I print a specific element of an array. For example I want it to go 5,4,3,2,1,0, but it keeps printing out the entire array instead.

  • 3
    What do you think `Arrays.toString(list)` does? – Scary Wombat Dec 13 '19 at 04:16
  • 1
    Does this answer your question? [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Molly Dec 13 '19 at 04:23
  • From what I can tell you wanted `i` **not** `Arrays.toString(list)`; or better `System.out.printf("Element %d is %d%n", i, list[i]);` – Elliott Frisch Dec 13 '19 at 04:24

3 Answers3

0
System.out.println("element is " + list[i]);

instead of

System.out.println("element" + (Arrays.toString(list))+"is " + list[i]);
0

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. So if you know the index of array you want to print, you can directly access it with index number as below:

System.out.println("element is " + list[i] + " at index " + i);

But looks like you want to print array elements starting from one specific index till 0 index. You can do that as below (lets assume starting index is 5 and you want o print 5,4,3,2,1,0 in reverse order):

int startIndex = 5;

if (list.length < (startIndex + 1)) {
        System.out.println("");
} else {

    for (int i = startIndex; i >= 0; i--) {
            System.out.println("element is " + list[i] + " at index " + i);
    }
}
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
0

You need to have list of indices you want to display as separate variable.

check_arr = [5,4,3,2,1,0]

Then in your loop you can check if index value is present in array (check_arr) then print.

To do same thing without if condition, you need to have a starting index for loop. provided that you want to display all values from one index till other (start to end).

for (int i = start; i >= 0; i--) {
        System.out.println(list[i] + " at index " + i);
}