1 Replies - 554 Views - Last Post: 14 November 2011 - 12:18 PM Rate Topic: -----

#1 iggyman11   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 05-October 11

cannot find variable i error

Posted 14 November 2011 - 12:16 PM

So the program's goal is to find the second highest value in an array that is supplied values through user input. My problem is that in the for loop an error in compilation keeps coming up telling me that it cannot find symbol - variable i. What am I doing wrong here?
import java.util.*; 

public class secondHighestNumber
{
    public static int readData(int[] x)
    {
        System.out.println("Enter a sequence of up to " + x.length + " integers.");
        System.out.println("Terminate the sequence with a value of -999.");
        
        Scanner input = new Scanner(System.in);
        int i;
        for (i = 0; i < x.length; i++)
        {
            x[i] = input.nextInt();
            if (x[i] == -999) break;
        }
        return i;
    }
    public static int secondHighest (int[] x)
    {
        int highest = x[0];
        int secondhighest = x[0];
        for (i = 1; i < x.length; i++)
        {
            if (x[i] > highest)
            {
                secondhighest = highest;
                highest = x[i];
            }
            else if (x[i] > secondhighest)
            {
                secondhighest = x[j];
            }
        }       
        return secondhighest;
    }
   public static void main(String[] args) 
    {   
        int[] elements = new int[100];
        int count = readData(elements);
        int second;
        second = secondHighest(elements);
        System.out.println("The second highest value in the array: "+ second);
    }
}


Is This A Good Question/Topic? 0
  • +

Replies To: cannot find variable i error

#2 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: cannot find variable i error

Posted 14 November 2011 - 12:18 PM

In your secondHighest() method you never define an integer 'i' for use in the loop.

In your other method where you do declare the integer, the scope of the variable is limited to that method only. You cannot access it from any other method.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1