Ошибка: java: not a statement
Тернарный оператор ?: в Java единственный оператор, который принимает три операнды.
логическоеВыржанеие ? выражение1: выражение2
Первый операнд должен быть логическим выражением. Второй и третий операнды — любым выражением, которое возвращает любое значение.
System.out.print() ничего не возвращает, поэтому и была ошибка.
Операнд — элемент данных, над которым производятся машинные операции.
Not a statement java ошибка что значит

int a, b, c, d, x = 4572;
a = x / 1000;
b = x % 1000 / 100;
c = x % 100 / 10;
d = x % 10;
System.out.println(x/(d+b));
> else
System.out.println(x/(c+a));
| Serge_Bliznykov |
| Посмотреть профиль |
| Найти ещё сообщения от Serge_Bliznykov |

Интенсив по Python: Работа с API и фреймворками 24-26 ИЮНЯ 2022. Знаете Python, но хотите расширить свои навыки?
Slurm подготовили для вас особенный продукт! Оставить заявку по ссылке — https://slurm.club/3MeqNEk
Understanding Common Errors In Java

When we were building our automated common error feedback feature on Mimir Classroom, we analyzed millions of stack traces that our students received when completing their coursework on our platform. In this post, you will find the errors we found to be most troubling to students in Java and some tips on how to approach them.
To start off, here is a quick refresher on how to read an error in the Java stack trace.

1. ’;’ expected
This error means that you forgot a semicolon in your code. If you look at the full error statement, it will tell you where in your code you should check within a few lines. Remember that all statements in Java must end in a semicolon and elements of Java like loops and conditionals are not considered statements.
2. cannot find symbol
This error means that Java is unable to find an identifier that it is trying to work with. It is most often caused by the following:
- You misspelled a variable name, class name, or a keyword somewhere. Remember that Java is case sensitive.
- You are trying to access a variable or class which does not exist or can not be accessed.
- You forgot to import the right class.
3. illegal start of expression
This error usually occurs when your code does not follow Java’s standard structure. Check the nesting of your variables and ensure that all your and ( ) are in the right place..
4. class, interface, or enum expected
This error is usually caused by misplaced . All code in Java needs to be contained within a class, interface, or enum. Ensure that all of your code is within the of one of those. We often have seen this error when there is an extra > at the end of your code.
5. reached end of file while parsing
This error usually occurs when you are missing a > somewhere in your code. Ensure that for every in the right place.
6. missing return statement
This error usually means one of two things:
- Your method is expecting a return statement but is missing one. Ensure that if you declared a method that returns something other than void and that it returns the proper variable type.
- Your return statements are inside conditionals who’s parameters may not be reached. In this case, you will need to add an additional return statement or modify your conditionals.
7. ‘else’ without ‘if’
This error means that Java is unable to find an if statement associated to your else statement. Else statements do not work unless they are associated with an if statement. Ensure that you have an if statement and that your else statement isn’t nested within your if statement.
8. ‘(‘ expected or ‘)’ expected
This error means that you forgot a left or right parenthesis in your code. If you look at the full error statement, it will tell you where in your code you should check. Remember that for every ( you need one ).
9. case, default, or ‘>’ expected
This error means that your switch statement isn’t properly structured. Ensure that your switch statement contains a variable like this: switch (variable). Also ensure that every case is followed by a colon (:) before defining your case.
10. ‘.class’ expected
This error usually means that you are trying to declare or specify a variable type inside of return statement or inside of a method calls. For example: “return int 7;» should be «return 7;»
11. invalid method declaration; return type required
Every Java method requires that you declare what you return even if it is nothing. «public getNothing()» and «public static getNumber()» are both incorrect ways to declare a method.
The correct way to declare these is the following: «public void getNothing()» and «public static int getNumber()»
12. unclosed character literal
This error occurs when you start a character with a single quote mark but don’t close with a single quote mark.
13. unclosed string literal
This error occurs when you start a string with a quotation mark but don’t close with a second quotation mark. This error can also occur when quotation marks inside strings are not escaped with a backslash.
14. incompatible types
This error occurs when you use the wrong variable type in an expression. A very common example of this is sending a method an integer when it is expecting a string. To solve this issue, check the types of your variables and how they are interacting with other types. There are also ways to convert variable types.
15. missing method body
This error commonly occurs when you have a semicolon on your method declaration line. For example «public static void main(String args[]);». You should not have a semicolon there. Ensure that your methods have a body.
16. unreachable statement
This error means that you have code that will never be executed. Usually, this is after a break or a return statement.
Types of Errors in Java with Examples
Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing.
The most common errors can be broadly classified as follows:
1. Run Time Error:
Run Time errors occur or we can say, are detected during the execution of the program. Sometimes these are discovered when the user enters an invalid data or data which is not relevant. Runtime errors occur when a program does not contain any syntax errors but asks the computer to do something that the computer is unable to reliably do. During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) that detects it while the program is running. To handle the error during the run time we can put our error code inside the try block and catch the error inside the catch block.
For example: if the user inputs a data of string format when the computer is expecting an integer, there will be a runtime error. Example 1: Runtime Error caused by dividing by zero
Ошибка компилятора Java: незаконное начало выражения
См. Примеры, иллюстрирующие основные причины ошибки “незаконное начало выражения” и способы ее устранения.
- Автор записи
1. Обзор
“Незаконное начало выражения”-это распространенная ошибка, с которой мы можем столкнуться во время компиляции.
В этом уроке мы рассмотрим примеры, иллюстрирующие основные причины этой ошибки и способы ее устранения.
2. Отсутствующие Фигурные Скобки
Отсутствие фигурных скобок может привести к ошибке “незаконное начало выражения”. Давайте сначала рассмотрим пример:
Если мы скомпилируем вышеуказанный класс:
Отсутствие закрывающей фигурной скобки print Sum() является основной причиной проблемы.
Решение проблемы простое — добавление закрывающей фигурной скобки в метод printSum() :
Прежде чем перейти к следующему разделу, давайте рассмотрим ошибку компилятора.
Компилятор сообщает, что 7-я строка вызывает ошибку “незаконное начало выражения”. На самом деле, мы знаем, что первопричина проблемы находится в 6-й строке. Из этого примера мы узнаем, что иногда ошибки компилятора не указывают на строку с основной причиной , и нам нужно будет исправить синтаксис в предыдущей строке.
3. Модификатор Доступа Внутри Метода
В Java мы можем объявлять локальные переменные только внутри метода или конструктора . Мы не можем использовать модификатор доступа для локальных переменных внутри метода, поскольку их доступность определяется областью действия метода.
Если мы нарушим правило и у нас будут модификаторы доступа внутри метода, возникнет ошибка “незаконное начало выражения”.
Давайте посмотрим на это в действии:
Если мы попытаемся скомпилировать приведенный выше код, мы увидим ошибку компиляции:
Удаление модификатора private access легко решает проблему:
4. Вложенные методы
Некоторые языки программирования, такие как Python, поддерживают вложенные методы. Но, Java не поддерживает метод внутри другого метода.
Мы столкнемся с ошибкой компилятора “незаконное начало выражения”, если создадим вложенные методы:
Давайте скомпилируем приведенный выше исходный файл и посмотрим, что сообщает компилятор Java:
Компилятор Java сообщает о пяти ошибках компиляции. В некоторых случаях одна ошибка может привести к нескольким дальнейшим ошибкам во время компиляции.
Выявление первопричины имеет важное значение для того, чтобы мы могли решить эту проблему. В этом примере первопричиной является первая ошибка “незаконное начало выражения”.
Мы можем быстро решить эту проблему, переместив метод calcSum() из метода print Sum() :
5. символ или строка Без кавычек
Мы знаем, что String литералы должны быть заключены в двойные кавычки, в то время как char значения должны быть заключены в одинарные кавычки.
Если мы забудем заключить их в соответствующие кавычки, компилятор Java будет рассматривать их как имена переменных .
Мы можем увидеть ошибку “не удается найти символ”, если “переменная” не объявлена.
Однако если мы забудем дважды заключить в кавычки Строку , которая не является допустимым именем переменной Java , компилятор Java сообщит об ошибке “незаконное начало выражения” .
Давайте посмотрим на это на примере:
Мы забыли процитировать строку |//+ внутри вызова метода equals , и + , очевидно, не является допустимым именем переменной Java.
Теперь давайте попробуем его скомпилировать:
Решение проблемы простое — обертывание String литералов в двойные кавычки:
6. Заключение
В этой короткой статье мы рассказали о пяти различных сценариях, которые приведут к ошибке “незаконное начало выражения”.
В большинстве случаев при разработке приложений Java мы будем использовать среду IDE, которая предупреждает нас об обнаружении ошибок. Эти замечательные функции IDE могут значительно защитить нас от этой ошибки.
Тем не менее, мы все еще можем время от времени сталкиваться с этой ошибкой. Поэтому хорошее понимание ошибки поможет нам быстро найти и исправить ошибку.
Java: Not a statement
I suppose this is more a question about language theory than anything else. Why is the first statement in main legal, when the second is not? Don’t they evaluate to be the same thing?
![]()
2 Answers 2
Java restricts the types of expressions that are allowed in so-called «expression statements». Only meaningful expressions that have potential side effects are allowed. It disallows semantically meaningless statements like 0; or a + b; . They’re simply excluded from the language grammar.
A function call like foo() can, and usually does, have side effects, so it is not a meaningless statement. The compiler doesn’t deeply inspect the body of foo() to check whether it actually does anything. Calling a function can have side effects, so it is syntactically valid.
This reflects a philosophical difference between C/C++ and Java. Java prohibits various constructs which result in dead or meaningless code.
C and C++ are relatively laissez faire about it all. Write whatever you want; they don’t have time to babysit you.
Certain kinds of expressions may be used as statements by following them with semicolons.
An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded.
Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.
Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements. Note that the Java programming language does not allow a «cast to void» — void is not a type — so the traditional C trick of writing an expression statement such as:
does not work. On the other hand, the Java programming language allows all the most useful kinds of expressions in expressions statements, and it does not require a method invocation used as an expression statement to invoke a void method, so such a trick is almost never needed. If a trick is needed, either an assignment statement (§15.26) or a local variable declaration statement (§14.4) can be used instead.