javaarraysdrjava

how do i get rid of the zero that shows up after all my elements in my array are listed?


i have to make a program that prints out the elements of an array filled with random numbers backwards but it also prints out a zero after my variables? i think it has something to do with my for-loops but i get a java.lang.ArrayIndexOutOfBoundsExceptionerror any time i try to change them.

edit: i also noticed that the first printed element is always zero. i don't really see it as a problem but what could be causing that?

import java.util.*;

public class EZD_printBackwards
{
    static int vars[] = new int[10];

    static int backwards()
    { 
        Random rand = new Random();
        int bkwds = vars[0];

        for (int a = 0; a < 10; a++) 
        {
            vars[a] = rand.nextInt(100)+1;
        }

        for (int x = 10; x > 0; x--)
        {
            System.out.println("Element " + x + " is " + vars[x] );      
        }
        return bkwds;
    }

    public static void main(String Args[])
    {

       int option;
       Scanner kbReader = new Scanner(System.in);

       do
       {
           System.out.println(backwards());
           System.out.print("Type 1 to run again. Type 0 to end the program.");
           option = kbReader.nextInt();

           while(option !=1 && option !=0)
           {

               if (option != 1 && option != 0)
               {
                   System.out.print("Please enter 1 to run again or 0 to end the program.");
                   option = kbReader.nextInt();
               }
           }

       }while(option==1);

       System.out.println("");
    }
}

Solution

  • You have two problems:

    FIRST => For loop out of bounds

    you want to go through 10 elements, therefore your

    for (int x = 10; x > 0; x--)
    

    should be

    for (int x = 9; x >= 0; x--)
    

    0..9 is 10 elements and the same things goes for

    for (int a = 0; a < 10; a++) 
    

    to

    for (int a = 0; a < 9; a++)
    

    SECOND ==> 0 at the end

    That's because you do

    System.out.println(backwards());
    

    instead of

    backwards();