/** 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 replies to this topic
#1
Posted 05 April 2011 - 09:27 PM
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?
|
|
|
#2
Posted 06 April 2011 - 02:44 AM
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.
If you want to access it from the main method, it will have to be static.
#3
Posted 06 April 2011 - 03:55 PM
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


Sign In
Create Account


Back to top









