I'm getting an error off of a segment of code which came from this forum.
While(scan.hasNext()) {
}
It says
';' expected
Please direct me in the right direction.
Your issue is that you've used 'While' instead of 'while' (it's case sensitive).
Your IDE has recognised that the method While doesn't exist, and has created it (unimplemented). It thinks that While is a method, makes that method, and then expects it to have the syntax of that method - of course, "while" is a construct and has a different syntax.
Related
I would think that the following Java code would cause a RuntimeError (technically speaking) because it is referencing something non-existent (much like accessing the 8th element in an array of size 5).
int i;
System.out.println(i);
However, the IDE catches it, underlining it in red. Does that make it a syntax/compiler error? Or a runtime error that the IDE is just smart enough to catch?
Actually, is it a compiler error but not technically a syntax error? I always thought of them as synonymous, but maybe syntax errors are just a type of compiler error...
I know it's just semantics, but I'm teaching a class and feel silly not knowing what type of error it technically is.
If int i; is declaring a local variable, it is a compilation error to use it before it is assigned to; see #Eran's answer for the relevant section of the JLS.
Compilation error and compile-time errors are synonyms. (Compiler error is another synonym, though sometimes people use that to refer to bugs in the compiler.)
Does that make it a syntax/compiler error?
It is a compilation error. But it is not a syntax error.
This type of compilation error is typically called a semantic error.
A syntax error means that the code doesn't conform to the language's specified syntax (as defined by the grammar). In other words, the parser can't parse it.
A semantic error is any compilation error that isn't a syntax error. Depending on the programming language, semantic errors may include such things as:
compile time type errors
symbols that cannot be resolved by the compiler
symbols that have the wrong kind for the context
unreachable code
use of uninitialized variables
and so on.
Or a runtime error that the IDE is just smart enough to catch?
It is not a runtime error.
Actually, is it a compiler error but not technically a syntax error?
Correct.
I always thought of them as synonymous, but maybe syntax errors are just a type of compiler error...
They are not synonymous. Syntax errors are just one kind of compilation error.
(Unfortunately some Javascript implementations confusingly refer to all compilation errors as "Syntax Error". But that is not relevant if you are teaching Java. Java is not Javascript.)
It's a compile-time error, as specified by the JLS:
14.4.2. Execution of Local Variable Declarations
A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable.
If a declarator does not have an initialization expression, then every reference to the variable must be preceded by execution of an assignment to the variable, or a compile-time error occurs by the rules of ยง16.
Have you tried compiling it without the IDE?
In Java it is detected as compile time error saying: error: variable i might not have been initialized
It's simple run time error. IDE would point that out, however if u run it you'll get some error like I needs to be initialise
I'm getting an compilation error "Not a statement" for this line of code:
parallel? stats[3]++ : stats[4]++;
can't understand why?!
Quoting from this:
The following types of expressions can be made into a statement
by terminating the expression with a semicolon (;).
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
...
In addition to expression statements, there are two other kinds of
statements: declaration statements and control flow statements.
Obviously, your line of code above doesn't fall into any category mentioned above. Hence, the compiler throw an error. Look at the outermost, not the innermost.
The :? operator is used to return a value is not a complete replacement for the if/else and you aren't returning a value. But explain better what is the complete error, and give a better look of the code not only the line that you post.
If I have a piece of code like this:
public class ABC {
public static void main(String[] args) {
if (true)
int a = 0;
}
}
When I compile it, Java compiler produces an error
.class expected.
I know that when we don't use braces, we can use only one statement after if.
And I also know that I will not be able to use the int variable a, because as soon as the ; is encountered, the program comes out of if, and the variable a loses it's scope.
I am not surprised that this code emits an error, but why is the error message '.class' expected?
What is Java compiler trying to say?
I suspect the problem is that the only token sequence that can legitimately follow the keyword token of int in this case is . followed by class. The declaration statement you've got at the moment isn't valid because a local variable declaration on its own isn't a Statement as per JLS 14. (It's a BlockStatement.)
Note that in the tutorialspoint environment referenced in the comment, if you use a class instead of int, a different error is produced - potentially because the set of valid tokens is different in that scenario. (String.getClass(); would be valid for example, whereas int.getClass(); wouldn't.)
There is a valid question asked in a comment:
Why this .class thing? If you know any situation in which int followed by .class can compile, then please tell me.
And that's easy - you can call a method on the Class reference returned by int.class:
public class ABC
{
public static void main(String args[])
{
if(true)
int.class.getName();
}
}
That's not useful code, but it is valid code. It compiles for me without warnings or errors.
As mentioned in comments, more recent compiler versions give more useful errors - I would recommend upgrading.
As opposed to what some commenters say, this code can actually produce that error.
int a = 0;
^
According to the Java Language Specification, a variable declaration needs to be in a code block:
Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.
I assume you already knew that.
But why the .class expected error?
The reason why the exception says .class expected, is compiler specific. Other compilers will emit not a statement or illegal start of expression.
My guess is that it is related to the way the compiler evaluates the code. The only way int can be valid at that location, is when followed by .class. So as soon as the token int is detected, the compiler expects it to be followed by .class.
For example,
if (true)
int.class.getFields();
would be a valid statement.
So the compiler gives an error that is in some way logical, that is, .class expected.
Other compilers probably evaluate the whole statement as a variable declaration, rather than separate tokens like int, a, = and 0.
Specific compiler
I do not know which specific compiler tutorialspoint.com is using, but their javac version (using javac -version) is javac 1.7.0_75 on Fedora release 21 (Twenty One) (using the command cat /etc/issue.net).
PS: I don't know if you have a specific reason for using the compiler of which you posted an image, but I suggest you start using Eclipse or Netbeans.
if(true)
String str;
Hi, the code above gives an error like that:
Multiple markers at this line
- str cannot be resolved to a variable
- Syntax error on token "String", AssignmentOperator expected after this token
Why there is an error like this? Of course I know str will be unreachable after defined. But java doesn't gives an explanation like that. Just seemed odd to me.
This is because you put a declaration in a protected block of the conditional. However, Java declarations are not considered statements according to Java syntax.
Declarations are allowed to be mixed with statements as part of blocks enclosed in curly braces, but a single declaration is not considered a statement. This makes perfect sense, because the variable that you declare is not usable: if you wanted a declaration-initialization for its side effect, such as
if (true)
String str = someFunction();
you could use an expression statement without declaring a variable that you wouldn't be able to use anyway:
if (true)
someFunction();
Therefore, if you put a declaration by itself in a conditional or a loop, the compiler is certain that you made a mistake, and produces an error message to alert you to the problem.
I am writing some Java questions to help my friends in
the Java exam. I wrote a question and I assumed
that three errors would occur in the code but the compiler
only complained about two. The code is:
class MyClass
{
static MyClass()
{
System.out.println("I am The First Statement here!");
this();
}
}
I expected the following errors:
the constructor can't be static
this can't be in a static function (since the constructor isn't valid)
this here should be the first
statement.
NetBeans isn't complaining about the second error here. Why?
When compilers encounter errors, they try to avoid so-called "secondary errors" - errors resulting from other errors, by "fixing-up" earlier errors.
For example, the compiler flags an error because of the malformed constructor declaration. It can interpret this as either a constructor, that you've tried to make static, or as a regular static method that is missing a declared return type. The compiler can fix up your declaration either by ignoring the static keyword, and treating it as a regular constructor, or it can treat it as a static method and "invent" a return type to make up for a missing return type.
It sounds like NetBeans is taking the first approach - fixing up your constructor so that it is not static. When the compiler chooses to ignore the static keyword, to avoid secondary errors, the this() call is then valid, since the compiler sees that it is in a regular constructor, so the second error is not flagged. This is actually desirable behaviour - compiler writers go to great lengths to avoid secondary errors, since they cloud the "real" errors. As soon as you fix up the static constructor yourself and remove the static keyword, the this() call will then be valid (barring error #3.)
To sum up - it's the compiler trying to show you the real errors, rather than all the subsequent problems caused by those errors.
EDIT: after an error, a compiler tries to recover by skipping over input to try to get back on track (to resync the tokenizer and parser to a known state). The portion they skip may have contained errors, or have caused an error in what the compiler subsequently correctly parses. Thus, error-recovery can lead to some errors not being reported. This is not significant from a correctness perspective - as long as the compiler flags one error (the original one that lead to error-recovery being required) that's sufficient. Error handling and error reporting is primarily about usability. A compiler would be equally correct if it just printed "error" at the first error and left you to figure out where the error is - it just wouldn't be very usable.
If I try this in IntelliJ, it gives me these messages:
Compilation completed with 2 errors and 0 warnings
(3, 11) modifier static not allowed here
(6, 12) call to this must be first statement in constructor
logically you are right, there are 3 errors in the code. However the compiler compiles the code in a sequential way. Unless the previous errors are gone it won't parse any deeper.
You must have disabled the in-time compiler setting. These are the compile time error. They must be shown.
Did you try running?