Return outside method error
defines a Java method called openingboard . This isn’t the case. Java follows the C paradigm of requiring you to specify your parameters in parentheses, regardless of whether you have any parameters or not. So, the method
is a valid Java method (assuming it is inside some class), as is a version of openingboard with much more code between the curly braces.
That said, I’m going to pass along a few friendly pointers on Java style:
- Java (and indeed most higher-level language) programmers tend to frown on «forever» loops such as while (true) , since those loops make it much harder to determine when the loop actually stops.
- There is no need for the label search in the code, and labels are even more discouraged than forever loops are.
So, I would recommend rewriting your code to look something like
private boolean openingboard() < Robot robot = new Robot(); Color color3 = new Color(108, 25, 85); Rectangle rect = new Rectangle(0, 0, 1365, 770); BufferedImage image = robot.createScreenCapture(rect); for(int x = 0; x < rectangle.getWidth(); x++) < for(int y = 0; y < rectangle.getHeight(); y++) < if(image.getRGB(x, y) == color3.getRGB()) return true; >> return false; >
assuming of course that you prefer a debugger to trace prints.
Solution 2
Proper methods look like: boolean openingboard ( )
not like boolean openingboard;
The parenthesis are not optional.
The way you have it: openingboard is a field. There is a init block with a Robot and a color and some for loops nested inside of each other. Inside one of the for loops is a return which is not allowed in an init block.
Возврат ошибки внешнего метода
ошибка: java: 71: вернуть внешний метод return true ^ я не знаю, что это происходит, помогите пожалуйста!
2 ответы
определяет метод Java, называемый openingboard . Это не так. Java следует парадигме C, требующей указывать параметры в круглых скобках, независимо от того, есть ли у вас какие-либо параметры или нет. Итак, метод
- Программисты на Java (и на самом деле, на большинстве языков более высокого уровня) склонны не одобрять «вечные» циклы, такие как while (true) , поскольку эти циклы значительно затрудняют определение момента, когда цикл на самом деле останавливается.
- Этикетка не нужна search в коде, а метки не приветствуются даже больше, чем бесконечные циклы.
Итак, я бы рекомендовал переписать ваш код, чтобы он выглядел примерно так:
private boolean openingboard() < Robot robot = new Robot(); Color color3 = new Color(108, 25, 85); Rectangle rect = new Rectangle(0, 0, 1365, 770); BufferedImage image = robot.createScreenCapture(rect); for(int x = 0; x < rectangle.getWidth(); x++) < for(int y = 0; y < rectangle.getHeight(); y++) < if(image.getRGB(x, y) == color3.getRGB()) return true; >> return false; >
при условии, конечно, что вы предпочитаете отладчик для отслеживания отпечатков.
Я не слышал много комментариев — ни положительных, ни отрицательных — относительно лейблов. Я бы счел их добрыми. Так почему же к ним относятся неодобрительно? — Эмери
@emory Если вы не используете метки для вложенной паузы или продолжения, метка не имеет абсолютно никакого значения, которое не предоставляет комментарий. В результате комментарий намного лучше согласуется с соглашением. Метка подходит для вложенных операторов break / continue, но не нужна по какой-либо другой причине. Я бы классифицировал метку Java с помощью C goto: это полезно для улучшения читаемости в очень ограниченном наборе обстоятельств, но не используйте ее за пределами этого набора. — Адам Михалцин
@emory Использование меток в значительной степени то же самое, что и операторы goto, которые считается вредным. — ТомасВ
Правильные методы выглядят так: boolean openingboard ( )
не как boolean openingboard;
Скобки не являются обязательными.
Как у вас это есть: открытая доска — это поле. Есть блок инициализации с роботом и цветом, а также несколько циклов for, вложенных друг в друга. Внутри одного из циклов for находится возврат, который недопустим в блоке инициализации.
return outside method
posted 5 years ago
Hello,
I am developing a dice game, I make a random draw with 5 dice since a call of my method of the main program which displays the result in a table of String.
an error comes to tell me «return outside method».
The program is so simple that I do not see my mistake is contradictory!
Here is a piece of my code:
Saloon Keeper
posted 5 years ago
This is incorrect syntax for declaring a method. Additionally, a method name should begin with a lower case letter.
posted 5 years ago
Carey Brown wrote:
This is incorrect syntax for declaring a method. Additionally, a method name should begin with a lower case letter.
I wrote my method begin with a lower case letter >> I always have the same problem !
Saloon Keeper
posted 5 years ago
Philippe Ponceblanc wrote:
Carey Brown wrote:
This is incorrect syntax for declaring a method. Additionally, a method name should begin with a lower case letter.
I wrote my method begin with a lower case letter >> I always have the same problem !
Did you fix the syntax error?
Saloon Keeper
posted 5 years ago
Sheriff
posted 5 years ago
- 2
There is no syntax error (see follow-up below): you’re just not declaring a method. Rather, you have declared a static class variable. If you format your code correctly, you’ll see what’s wrong.
You probably did not intentionally do this but lines 5-12 above is an instance initialization block.
Saloon Keeper
posted 5 years ago
definition of «syntax error»
«a character or string incorrectly placed in a command or instruction that causes a failure in execution [or compilation].»
Sheriff
posted 5 years ago
- 1
Sorry, there is in fact a syntax error at the line OP indicated and it’s because a return statement is not allowed in an initializer block.
Bartender
posted 5 years ago
And what is this line supposed to mean:
You do not show a class named ToString. Did you mean PokerDAs instead?
Did you mean for Tirage to be the name of a method that returns a String array (in which case you have an extraneous semicolon and no argument list for the method.
And if that is the case, why do you return an array of ints instead of an array of Strings?
posted 5 years ago
can not return a arrays in my method, the compiler tells me
>> return outside method!
posted 5 years ago
Yes. There is no method there. See Junilu Lacar’s post.
Here it is again:
Get rid of the ; on line 1 above and make it a proper method declaration statement.
posted 4 years ago
I have spotted the following when I run your code,
the first is that you mix up the int[] and string[] arrays in your method. Once you instantiate it as a string or int, you either have to convert those and save it in a different variable or keep it the same type.
The 2nd is that you created a method signature (non declared method) to be overwritten by classes that could implement/extend the class, so the method can not have a return.
Example of the difference:
public static void overrideMe;
public static String giveMeString()< //code >;
When you managed to fix these, you may want to look at how to change line 13 to call a static method.
Return outside method error
defines a Java method called openingboard . This isn’t the case. Java follows the C paradigm of requiring you to specify your parameters in parentheses, regardless of whether you have any parameters or not. So, the method
is a valid Java method (assuming it is inside some class), as is a version of openingboard with much more code between the curly braces.
That said, I’m going to pass along a few friendly pointers on Java style:
- Java (and indeed most higher-level language) programmers tend to frown on «forever» loops such as while (true) , since those loops make it much harder to determine when the loop actually stops.
- There is no need for the label search in the code, and labels are even more discouraged than forever loops are.
So, I would recommend rewriting your code to look something like
private boolean openingboard() < Robot robot = new Robot(); Color color3 = new Color(108, 25, 85); Rectangle rect = new Rectangle(0, 0, 1365, 770); BufferedImage image = robot.createScreenCapture(rect); for(int x = 0; x < rectangle.getWidth(); x++) < for(int y = 0; y < rectangle.getHeight(); y++) < if(image.getRGB(x, y) == color3.getRGB()) return true; >> return false; >
assuming of course that you prefer a debugger to trace prints.
Adam Mihalcin
Proper methods look like: boolean openingboard ( )
not like boolean openingboard;
The parenthesis are not optional.
The way you have it: openingboard is a field. There is a init block with a Robot and a color and some for loops nested inside of each other. Inside one of the for loops is a return which is not allowed in an init block.