This site requires JavaScript, please enable it in your browser!
Greenfoot back
divinity
divinity wrote ...

2016/2/12

help with this array program

divinity divinity

2016/2/12

#
hi been doing this program and keep getting this error.
 public static int getLargest(int num[])
    {
        int i, largest=0;
        
        for(i=1; i<5; i++)
        {
            if(i==0)
            {
                largest = num[i];
            }
            else if(num[i]> largest)
            {
                largest = num[i];
            }
        }
        return largest;
    }
    
    public static void displayFactors(int num[])
    {
        int i, n;
        
        for(i=0; i<=5; i++)
        {
            System.out.println("factors of "+num[i]);
        }
        System.out.println("");
        
        for(n=1; n<=num[i]; n++) ( the problem is there. dont know if it is an array outofboundexception error.
        {
            if(num[i]%n == 0)
            {
               System.out.println(n);
            }
        }
    }
    
    public static void reversed(int num[])
    {
        int i;
        
        System.out.println("\n numbers in reserved orders");
        
        for(i=5; i>=0; i--)
        {
            System.out.println(num[i]);
        }
    }
      

    public static void main(String[] args) 
    {
        Scanner userinput = new Scanner(System.in);
        
        int num[] = new int[6];
        
        int i;
        
        for(i=1; i<=5 ; i++)
        {
            System.out.println("the largest number is "+getLargest(num));
        }
        displayFactors(num); (the problem is here also.
        reversed(num);
    }
all it is saying display factor at 38 and 72 any help would be appreciated
danpost danpost

2016/2/12

#
It sure looks like it would be an arrayOutOfBounds exception. Lines 23 through 26 cause the values in your array to be printed to the terminal, leaving the value of 'i' at '6'. You probably just need to remove and insert lines 26 and 27 at line 36. Having line 21 in your code helped to produce your issue. It is best to declare 'for' loop counter variables in the 'for' statement itself unless you need the value beyond the loop. You can remove line 21 and change your 'for' statements to these:
// first one
for (int i=0; i<=5; i++)
// second one
for (int n=1; n<=num[i]; n++)
If you had done this, your error would have pointed to 'i' not being found at line 29. This, in turn, would have you wonder why 'i' is not recognized at that line (because the loop with 'i' as its counter ended prematurely).
You need to login to post a reply.