Jump to content

Trouble with this method that calls an array

- - - - -

  • Please log in to reply
2 replies to this topic

#1
scottbomb

scottbomb

    Newbie

  • Members
  • PipPip
  • 21 posts
Hey all. I'm trying to write a simple method from a self-test problem in the book Absolute Java, ch. 6. I can't figure out what I'm doing wrong here, even though the line the compiler is complaining about is almost exactly like the answer in the book. The error is "illegal start of expression" where I define the isOutOfOrder method. I must be missing something obvious here. Any ideas?

 /** Returns -1 if the array's elements are in numerical order.

 *  Returns the value of i for the element that's not in order.

public class OutOfOrder

{

	public static void main(String[] args)

	{

		double[] test = {1.2, 2.1, 3.3, 2.5, 4.5, 7.9, 5.4, 8.7, 9.9, 1.0};


		public int isOutOfOrder(double[] array) // Compile error "illegal 

                                                                            start of expression".

		{

			double check = array[0];

			for (i = 0; i < array.length; i++)

			{

				if (i < check) return (i);

				else check = array[i];

			}

			return (-1);

		}

	System.out.println(isOutOfOrder(test));

	}

}



#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
You can't define a method (isOutOfOrder) in another method (main). It should be outside the main method, in the class.
If you want to access it from the main method, it will have to be static.

#3
scottbomb

scottbomb

    Newbie

  • Members
  • PipPip
  • 21 posts
Thanks! Now it works (after killing my other bugs too).
public class OutOfOrder

{

	public static int isOutOfOrder(double[] array) 

		{

			double check = array[0];

			for (int i = 0; i < array.length; i++)

		{

			if (array[i] < check) return (i);

			else check = array[i];

		}

		return (-1);

	}

	public static void main(String[] args)

	{

		double[] test = {1.2, 2.1, 3.3, 2.5, 4.5, 7.9, 5.4, 8.7, 9.9, 1.0};

		System.out.println(isOutOfOrder(test));

	}

}





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users