Class, interface, or enum expected - java

/********************************************
// Problems.java
\\
// Provide lots of syntax errors for the user to correct.
\\
********************************************/
public class Problems
{
public static void main(String[] args)
{
System.out.println ("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println ("This program still has lots of problems,");
System.out.print ("but" + "," + " if it prints this, you fixed them all.");
System.out.println (" *** Hurray! ***");
System.out.println ("!!!!!!!!!!!!!!!"+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
I'm quite new here and am wondering what is wrong with the code. All it does is show text, but when I compile it, I get an error "Class, interface, or enum expected".
It says there's something wrong with the last line (where the last } is). I'm not sure what is wrong here.
This assignment is for my computer science class. We were supposed to fix a few syntax errors (I do have bad eyes, so I might have not seen things like semicolons) and compile it and run, but it won't compile.
I was using JCreator 4.5 for this. I also tried compiling it at school and with a DOS prompt. HELP!

Based on the error you provided
'Problems', are only accepted if annotation processing is explicitly requested (according to the DOS/cmd prompt)
your command line arguments may be wrong, there is a post about this error in the following article
http://docs.oracle.com/javase/tutorial/getStarted/problems/
The exact qoute being
Class names, 'HelloWorldApp', are only accepted if annotation
processing is explicitly requested
If you receive this error, you forgot to include the .java suffix when
compiling the program. Remember, the command is javac
HelloWorldApp.java not javac HelloWorldApp.

This is how I compile your code. Try to recreate my steps and say if you get any errors.
Since this class is not in any specific package I created Problems.java file in d:\java tests. This file contains
/********************************************
//Problems.java
\\
//Provide lots of syntax errors for the user to correct.
\\
********************************************/
public class Problems
{
public static void main(String[] args)
{
System.out.println ("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println (" This program still has lots of problems,");
System.out.println ("but" + "," + " if it prints this, you fixed them all.");
System.out.println (" *** Hurray! ***");
System.out.println ("!!!!!!!!!!!!!!!"+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
I used UTF-8 coding.
Next in console I went to d:\java tests> and from this directory I used
d:\java tests>javac Problems.java
(you need to add .java suffix in class name here) which successfully created Problems.class file. To run main method from this class I used
d:\java tests>java Problems
(no suffixes here) which printed
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
This program still has lots of problems,
but, if it prints this, you fixed them all.
*** Hurray! ***
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Related

Forcing java to make a compile error with the user input as message

I Don't know whether it is possible in java or not; I want to get an input from user (from System.in) and then throw a compile error with that input. I mean if the user inputted the text "HELLO" then the program should throw a compile error: Compile Error: HELLO. I want an error that actually make the program stop executing at that point with that message.
Is this possible? If yes, How?
Actually I want to make a compile error during run-time!
The code will be like this:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
//compileError(str); this part must be completed
}
}
Is this possible?
What you are referring to is Exceptions not a compilation error. Compilation error is when there is something wrong in the syntax of your code and the Java compiler fails to generate byte code for your program for the JVM to execute it. So that happens before you can run the program.
So you can use an instance of a RuntimeException or any sub class of it in Java to terminate your program when "HELLO" is used as the input, here in my sample code InputMismatchException is thrown if the input is "HELLO", this exception being a sub class of RuntimeException or unchecked exception doesn't require the programmer to add a throws clause or handle it explicitly:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
if("HELLO".equals(str)){
throw new InputMismatchException("This input is not allowed");
}
}
You can make your program stop executing at that point. For example:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
if (str.equals("HELLO")) {
System.out.println("Compile Error: " + str);
System.exit(1);
}
// Do something else.
}
}
Another way to do it is to throw an exception ... except than you will get an exception stacktrace as well as a message. In the context you are doing this, it probably doesn't matter.
Note that there are some potential problems with this:
If the judge intercepts all output, then it may not be possible to get hold of the messages that your application produces.
The judge may feed your application different inputs each time it judges it.
However, this is not a real compile error. Indeed, it doesn't make sense for your program to generate a real compile error.
Compile errors occur when code is being compiled, and they are output by the compiler. But a Java application cannot read input (from the user or the "judge") at compile time. It can read input at runtime ... but then it is too late for a compilation error.
You seem to have your terminology confused. I suggest you read these articles to understand what the various terms mean:
Compilation Error or Compiler Error - https://en.wikipedia.org/wiki/Compilation_error
Runtime Error - https://techterms.com/definition/runtime_error
Exception - https://techterms.com/definition/exception
Your commented thus:
Think that you are given a program that you don't know what it should do and it pass some tests on an online judge. You know what the input could be but don't know in which order they come and you should get the test cases without actually accessing the online judge's test cases. I want to make my program give me some errors to find out what is in each test case.
and
I just have a working program and want to extract the input from online judge.
That is not a compilation error you are talking about. That is a runtime error, because you want / need it to happen when your program runs. Please refer to the links above for explanations of these terms.
If your intent is to print a message and exit out of program you can do something like following
...
System.err.println("Your input has resulted in an error, program will terminate");
/* You can change the above text with whatever you want */
System.exit(1);
Alternately, you can always throw an object of Exception (or an object of a class derived from it) and don't catch it anywhere in your program when it bubbles, program will terminate.
/* add throws Exception in your main method */
throw new Exception("Your input has resulted in an error, program will terminate")
However it's not clear why you would specially look for throwing Compile error. Compile time errors are thrown by compiler when compiling a program. During execution you neither expect them nor try to throw them.
You cannot throw a compile error when your code is executing. I think you meant a Runtime error that cause your code to fail at runtime.
Try something like this:
throw new RuntimeException(str);
You can also catch this 'error' if you surround your code with try/catch clauses.
try {
// get the input
throw new RuntimeException(str);
} catch (RuntimeException ex) {
// ex contains the error details
// ex.getMessage() will give you the user's input
}
RuntimeException is the most general exception for errors at runtime, you can use other exceptions, list of exceptions.

Java - Error message showing question marks instead of characters

$ javac Increment.java
Output:
Increment.java:6: ??: ?????
System.out.println(++a++);
^
??: ??
??: ?
1 ???
here is the code
class Increment{
public static void main(String[] args) {
int a = 5;
System.out.println(++a++);
}
}
Does any one know what may be happening and how to fix it?
Increment is just a class for testing so that a error will appear.
I am running it in git-bash terminal, but I have tried it in cygwin terminal and windows's terminal as well.
character-set is UTF-8.
Most probably you have a national locale set up (e.g. Russian, Chinese or anything else) that makes the Java compiler to return nationalized error messages, but your terminal (cygwin) does not support the UTF-8 output or your system does not support UTF-8 locale.
As the quickest work-around you could switch java compiler to provide error messages in English:
$ javac -J-Duser.language=en Increment.java

Stop Eclipse from generating bytecode for code that doesn't compile

Eclipse happily generates bytecode for Java classes that have compilation errors. The offending methods just throw exceptions when invoked at runtime.
Does anyone know how I can stop Eclipse from generating bytecode when compilation errors are present? I'd rather not have runnable code at all in the presence of errors.
As an example, consider the following code:
public class Err {
public static void main(String[] args) {
methodWithoutCompilationError();
// methodWithCompilationError();
}
private static void methodWithoutCompilationError() {
System.out.println("No error here, folks.");
}
private static void methodWithCompilationError() {
System.out.println("This method doesn't compile." + );
}
}
It runs fine, even with the compilation error. Only when I uncomment the second line of main do I see there was a problem compiling.
The reason Eclipse does this is that the compile errors might be resolved by editing another java source file. For example, if a reference to a method name in another class is misspelled, the fix could be that you correct the spelling of the reference or the fix could be that you change the name of the method. Eclipse doesn't know which you'll choose to do so it compiles the referencing class anyway in case you decide to change to other file. I'm not even sure it could otherwise know when to compile all of the classes again.
As a result, Eclipse will always compile the edited java source to the extent possible whenever you change the source file.
I'm guessing at some point you enabled the 'Continue launch if project contains errors' option. Try setting it to 'Prompt':
Try checking the "Treat above errors like fatal compile errors (make compiled code not executable)" checkbox.

A URL specified in a separate line in Java doesn't issue compile-time errors. Why?

Some days age, I mistakenly pasted a URL in my Java program in a hurry, I attempted to run that specific program and in my curiosity, it ran successfully with no warnings, no errors and no exceptions. The similar code is as shown below. I compiles and runs successfully.
final public class Main
{
public static void main(String[] args)
{
System.out.println ("A curiosity");
https://localhost:8181/OnlineShoppingCartSystem-war/Restricted/Home
System.out.println ("compiled Ok!");
}
}
At the second line within the main() method, it should issue some compile-time errors but it works well and displays the respective messages on the console. Why?
The tokens https: gets interpreted as a label. And the // that follows starts a new-line comment. So, the posted code continues to be valid Java (if you notice the syntax coloring).
Because // starts a comment and https: is interpreted as a label.
This is because it looks like this to the compiler:
https: is a code label
//localhost:8181/OnlineShoppingCartSystem-war/Restricted/Home - is a comment
notice that the code highlighter works here as well as in your question.

need assistance on compile error with basic java program

I am brand new to Java. I am having an issue compiling a basic java program, and I am trying to understand why. (note that the TextIO class in the code is used in book I am studying to simplify the IO process, I don't believe that is where the issue is) Here is my code:
public class ProcessSales {
public static void main(String[] args) {
String ln;
String tmp;
int i;
int noval;
TextIO.readFile("sales.dat");
while (TextIO.eof() == false){
ln = TextIO.getln();
for (i = 0; i < ln.length(); i++) {
if (ln.charAt(i) == ':'){
tmp = ln.subString(i + 1);
}
} // end line for loop
try {
System.out.printf("%8.2f\n", Double(tmp.trim()));
}
catch (NumberFormatException e) {
noval++;
}
} // end of file while loop
System.out.printf("\nThere were a total of %d cities that didnt have data\n", noval);
} // end of main subroutine
} // end of ProcessSales class
The compile error I get is as follows:
[seldon#PrimeRadiant Exercises]$ javac ProcessSales.java
ProcessSales.java:15: cannot find symbol
symbol : method subString(int)
location: class java.lang.String
tmp = ln.subString(i + 1);
^
ProcessSales.java:20: cannot find symbol
symbol : method Double(java.lang.String)
location: class ProcessSales
System.out.printf("%8.2f\n", Double(tmp.trim()));
^
2 errors
Ive declared ln as a String object. The subString method is straight out of the java api for a String object. I'm not understanding why I'm getting a cannot find symbol compile error, especially if it lists the method signature and location right below the error.
I marked the questions as homework, since I am working out of a textbook, and I am looking to understand the issue, rather than a flat solution. However it is self study, and not part of any actual class (right now).
The great thing about the Java compiler is, it gives you alot of information to use in determining where problems exist in your code. For you, the first problem is here:
tmp = ln.subString(i + 1);
In this case you capitalized a letter that you shouldn't have. It should be:
tmp = ln.substring(i + 1);
Whenever you see compiler output saying 'cannot find symbol' its because the Java compiler could not find a method matching the outputted name, either due to a syntax error or missing dependency. For your second problem, you didn't post the appropriate code, but from the error message I can see you are missing the new keyword.
System.out.printf("%8.2f\n", Double(tmp.trim()));
Should be
System.out.printf("%8.2f\n", new Double(tmp.trim()));
If this is not your first programming language then I would recommend using an IDE like Eclipse, as it will give you auto-completion and syntax checking. It's a great tool for quickly learning the API's for the language. However if Java is your first programming language please do continue without hand-holding, as the hard knocks will cement in the lessons learned, faster.
I haven't verified any of this, I just looked at the source and the error messages.
The first error seems to be a case error. The Java String class does not have a subString method, it has a substring method, note the lowercase s. Reference
The second error would probably be resolved if you used new Double or Double.valueof instead of Double. This is because you are probably trying to construct a new Double object and using new operator or the valueof method in the Double class do this for you. Reference
In Java, method names are case sensitive. Check back with the String API specification for the correct "casing".
Regarding your first error, you have a typo. It should be ln.substring(i+1) not ln.subString(i+1). All source code text in Java is case sensitive.
Regarding your second error, you need to use the new keyword to instantiate the Double object. Without new, the compiler is not looking for the constructor; instead it is looking for a method Double within your ProcessSales class and cannot find it.

Categories

Resources