Illegal start of expression inside if statement using objects - java

I'm having a very frustrating issue at the moment and perhaps the answer lies here?
I'm currently having an issue with if statements.
I want my core.java class to contain an if statement which closes the entire program if my variable counter reaches 2.
private int counter = 0;
//located in the class Ending
I implemented that using a seperate method addCounter()
which goes as
public void addCounter(){
this.counter ++;
}
//this will be called in core.java
I also have a getter which is supposed to return the value of counter
public int getCounter(){
return counter;
}
//this will be called in core.java
Decleration of changeState in core.java
Ending changeState = new Ending();
//(As per request)
The real issue is described here:
I can't seem to come up with a fitting if statement which checks if the method getCounter has reached '2' after addCounter();has been invoked several times
My first idea was to use something such as
if(changeState.getCounter().equals(2)){
System.exit(0);
}
//I also tried using:
if(changeState.getCounter() == 2)
//however, that didn't work either
both lines give me numerous errors which I can't wrap my head around:
.java:476: error: illegal start of type: if(changeState.getCounter().equals(2)){
.java:476: error: <identifier> expected: if(changeState.getCounter().equals(2)){
.java:476: error: ';' expected: if(changeState.getCounter().equals(2)){
.java:476: error: illegal start of type: if(changeState.getCounter().equals(2)){
.java:476: error: illegal start of type: if(changeState.getCounter().equals(2)){
.java:476: error: ';' expected: if(changeState.getCounter().equals(2)){
Could anyone elaborate on what is going wrong and what should be done to overcome this issue?
Thank you in advance!
C.C.

.equals(2) is incorrect , the 2 in the equals method is a primitive type int literal not an Object or String type.
.equals() method uses either a type "String"
counter.equals("2")
or it uses a type "object" to compare
.equals(((Object)new String("2")))
If you must use .equals() method then it would be
if(counter.getCounter().equals(new Integer(2).toString())){
System.exit(0);
}
Although that really should be simpler such as
if(counter.getCounter() == 2){
System.exit(0);
}

My answer lied here all along.
If anyone else is having similar kind of issue, it seems that you simply can't invoke an object inside a class unless it's in a method.
I admit that this does solve my issue entirely, but it did show me a valuable lesson.
Good luck!

Related

Antlr4: Confusing error message (concatenates correct and incorrect lines) for Java grammar

I am trying to build my own parser based on the existing Java grammar.
Even if I use the Java7 grammar from the source repo, generate the parser and use the TestRig from antlr-4.9.3-complete.jar given the code:
1 public class Test {
2 public static void main() {
3 test
4 int b = 1;
5 }
6 }
I get the following error:
line 4:8 no viable alternative at input 'test\n int'
So for some reason it concatenates the incorrect "test" line with correct "int" line.
Also it says "line 4:8" pointing at the "int" line when it should be pointing to "test" (line 3).
(In a regular Java editor I would see a correct error highlighting for the "test" word which would sound like):
"Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration"
What do I do to arrive at a similar error with ANTLR so it only picks on the wrong "test" line?
Most likely it's just my misunderstanding how antlr interprets the errors, then how would I get the listener to at least report correctly the starting line?
You can't compare a sophisticated editor/IDE with a parser (generated by ANTLR). A text editor/IDE knows more about the input source and can look up if test is a valid type, and give a meaningful error message if the type cannot be found.
ANTLR's parser rule "sees" test int b as an Identifier, an INT and another Identifier token and cannot match any parser rule for these tokens, resulting in the error starting at the identifier test.
For example, if class test {} was in the classpath, then input without int would be valid:
public class Test {
public static void main() {
test
/*int*/ a = 1;
}
}
It wouldn't compile of course, but the syntax would be correct:

Learning the JAVA,but i'm in trouble

I start learning the JAVA,and I thought that it's more simple than C and more difficult than C#,so I have builded a project which using the JERSEY framework,and there some errors,would you like to help me fixed that errors?
here is my code
https://github.com/abcdef123ghi/jerseytest
I have 5 errors,I dont know what's diffrenet with JAVA & C#,I'm just triing to write a JAVA project,the error is
Description Resource Path Location Type
The method checkAuth(String, String) is undefined for the type myresource myresource.java /slwebservice/src/service line 40 Java Problem
Description Resource Path Location Type
The method inserttherecord(String, List<invdatas>) is undefined for the type myresource myresource.java /slwebservice/src/service line 43 Java Problem
Description Resource Path Location Type
The operator == is undefined for the argument type(s) int, null myresource.java /slwebservice/src/service line 31 Java Problem
Description Resource Path Location Type
This method must return a result of type int invdataManager.java /slwebservice/src/domain line 88 Java Problem
Description Resource Path Location Type
Type mismatch: cannot convert from java.util.Date to java.sql.Date invdataManager.java /slwebservice/src/domain line 223 Java Problem
thanks
regards
Ken
There are few compile errors in your code. I think you better follow some java tutorials and check the code again. Anyway I'll point out the errors and the solutions.
The method checkAuth(String, String) is undefined : There is no checkAuth method in your myresource.java. Please add it.
The method inserttherecord(String, List) is undefined : Same as above
The operator == is undefined for the argument type(s) int, null : int is a primitive value. So the default value for int is 0. If you used Integer instead of int, then your operation is correct. So you need to change the code as this.ivm.getRecordcount()==0
This method must return a result of type int : The method public int inserttherecord(List<invdatas> invdatalist,String clino) should return a int value. Your code does that but inside conditions and blocks. The idea is you should return a int value not you may return it. Al least put return 0; to the end of the method.
Type mismatch: cannot convert from java.util.Date to java.sql.Date : Here your method private Date parseDate(String date) should return java.sql.Date object But you return return format.parse(date);. This will return a java.util.Date. I think the return type of the method should be java.util.Date. It seems you import wrong class. Just import java.util.Date instead of java.sql.Date.
Hope this will help you. Thanks

Operand Missing Variable

int curFreeFrame = FrameTableEntry numFreeFrames();
The error states this "error ';' expected".
Everything is initialized correctly in the methods.
If you mean to invoke a static method, it should be :
int curFreeFrame = FrameTableEntry.numFreeFrames();
This assumes that numFreeFrames is a static method in FrameTableEntry class (which is an assumption based entirely on the naming conventions you used).
The obvious error is that you are missing the . so FrameTableEntry.numFreeFrames(); makes more sense than FrameTableEntry numFreeFrames();.
Now, with that said, if you're still getting an error, it might that you haven't initialized the FrameTableEntry class.
You can do so by FrameTableEntry f = new FrameTableEntry() and then use it's method numFreeFrames() by doing int curFreeFrame = f.numFreeFrames();.

Having trouble generating code attribute

I am trying to generate a method named hello that returns the value 2 using dynamic bytecode generation. This is my current code. To generate the method.
dout.writeShort(Modifier.PUBLIC);//class modifier
dout.writeShort(classConstant("test"));//class name
dout.writeShort(classConstant(Object.class.getName()));//superclass
dout.writeShort(0);//interface count
dout.writeShort(0);//field count
dout.writeShort(1);//method count
dout.writeShort(Modifier.PUBLIC|Modifier.STATIC);//modifiers
dout.writeShort(utfConstant("test"));//name
dout.writeShort(utfConstant(methodDescriptor(int.class, new Class[]{})));//descriptor
dout.writeShort(1);//attribute count
dout.writeShort(utfConstant("Code"));//attribute name
dout.writeInt(34);//attribute length
dout.writeShort(1);//max stack
dout.writeShort(0);//max locals
dout.writeInt(2);//code length
dout.writeByte(0x05);//iconst_2 opcode
dout.writeByte(0xAC);//ireturn opcode
dout.writeShort(0);//exception count
dout.writeShort(0);//attribute count
dout.writeShort(0);//class attributes
The problem is that when i run this code, i get this exception
Exception in thread "main" java.lang.ClassFormatError: Invalid method Code length 0 in class file test
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at Bytecode.BytecodeTest$BytecodeClassLoader.buildClass(BytecodeTest.java:229)
at Bytecode.BytecodeTest.makeClass(BytecodeTest.java:42)
at Bytecode.BytecodeTest.buildClass(BytecodeTest.java:27)
at Bytecode.BytecodeTest.main(BytecodeTest.java:19)
The weird thing is i am making the code length greater than 0 i am making it 2. I went back through the oracle specification but it still looks right. I have a feeling that i am writing some of the data as the wrong type, but i still cant find a problem.
An undocumented feature of the Hotspot verifier is that for versions <= 45.2, it uses shorter field lengths for some of the fields in the code attribute. That's why changing the version to 49 fixed everything.
If you use Krakatau, it will automatically take care of this, but I haven't seen any other tools that handle this case.
Luckily, the first stable public version of Java was 45.3, so you are unlikely to see legitimate code like this in the wild. But it is a neat trick for foiling reverse engineers.
Well, one thing that strikes me is the attribute length: by my count, it should be 14 (not 34). You also seem to be missing the class attribute count.
It would probably help you to define a couple helper methods for writing attributes, to ensure that you are computing and writing the length correctly, e.g., something like this:
private int writeAttribute(final String attributeName) {
dout.putShort(utfConstant(attributeName));
dout.putInt(0);
return dout.position();
}
private void endAttribute(final int attributeStart) {
dout.putInt(attributeStart- 4, dout.position() - attributeStart);
}
private void writeCode() {
final int codeAttributeStart = writeAttribute("Code");
dout.writeShort(1);//max stack
dout.writeShort(0);//max locals
dout.writeInt(2);//code length
dout.writeByte(0x05);//iconst_2 opcode
dout.writeByte(0xAC);//ireturn opcode
dout.writeShort(0);//exception count
dout.writeShort(0);//attribute count
endAttribute(codeAttributeStart);
}
Also, make sure the classfile minor/major version you're writing out matches the specification you're following--the format does change from time to time :).

Compiler warning when casting to generic method type variable in Java

Edit: I initially accepted thejh's answer, but I wasn't really satisfied with it since I wanted to make proper use of generics. So, I kept doing research and found a solution. Read about it in my answer below.
Here's a little self-contained piece of Java code which shows what I'm trying to do. It compiles, runs, and behaves correctly.
1 import java.lang.reflect.Method;
2 import java.lang.reflect.InvocationTargetException;
3
4 public class Example
5 {
6 public static <T> void foo(Method method, String target, Object argument, T expectedReturn) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
7 {
8 T actualReturn = (T) method.invoke(target, argument);
9 System.out.print(actualReturn.equals(expectedReturn));
10 }
11
12 public static void main(String[ ] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
13 {
14 foo(String.class.getMethod("charAt", int.class), "test", 1, 'e');
15 }
16 }
Running this prints true to the console, which is what I expected. What's bothering me is that, due to the cast on line 8, I'm getting a warning when I compile it, as follows (jGRASP is my IDE, by the way).
----jGRASP exec: javac -g -Xlint:unchecked Sandbox.java
Sandbox.java:8: warning: [unchecked] unchecked cast
found : java.lang.Object
required: T
1 warning
----jGRASP: operation complete.
Originally, I tried line 8 without the cast, but that failed to compile with an error complaining about finding an Object when it required T (invoke returns an Object). Later on, I rewrote it like this, blindly hoping to get rid of the warning.
T actualReturn = method.getReturnType( ).cast(method.invoke(target, argument));
But that gives a compile error that I can't make head nor tail of.
----jGRASP exec: javac -g -Xlint:unchecked Sandbox.java
Sandbox.java:8: incompatible types
found : capture#898 of ?
required: T
1 error
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
And that number next to capture# is different each time I try to compile with that same line of code.
So, what exactly is the problem? Why am I getting the warning when I cast the object returned by invoke to the type variable? Does that indicate that I'm doing something wrong? How can I write this so that the warning goes away? And I'd prefer not to suppress it with an annotation, as that doesn't seem like much of a solution to me.
I looked into this some more and found that I could solve the problem by using class literals as runtime type tokens, as discussed in the Java Tutorials.
I had the right idea with method.getReturnType( ).cast(...), but it didn't work because the return type of getReturnType( ) is Class<?>, and I needed Class<T>.
So, here's what the method looks like now.
public static <T> void foo(Class<T> returnType, Method method, String target, Object argument, T expectedReturn) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
{
T actualReturn = returnType.cast(method.invoke(target, argument));
System.out.print(actualReturn.equals(expectedReturn));
}
And here's a sample call.
foo(Character.class, String.class.getMethod("charAt", int.class), "test", 1, 'e');
That compiles without warnings and prints true to the console. Note that if you're expecting the underlying method to return a primitive, the returnType parameter needs to be its respective wrapper class.
Why do you cast it to T? Why don't you do it this way?
Object actualReturn = method.invoke(target, argument);
System.out.print(actualReturn.equals(expectedReturn));
Oh, and in case the method could return null and expectedReturn isn't, this is better:
Object actualReturn = method.invoke(target, argument);
System.out.print(expectedReturn.equals(actualReturn));
So, what exactly is the problem? Why
am I getting the warning when I cast
the object returned by invoke to the
type variable?
Method can return any Object. And it can't be cast to T in all cases.
Does that indicate that I'm doing
something wrong?
it's bad practice to mix reflection and generics, imho.
How can I write this so that the
warning goes away?
Personally, I think you can't avoid this warning without refactoring.

Categories

Resources