"Selection does not contain any Java files" from eclipse - java

Below my Test.java which is one .java file from a student project. I don't see why eclipse gives me
" Selection does not contain any Java files " error when I tried to "run" it from the menu Run-->Run ? Could you explain why?
This post
Java launch error selection does not contain a main type
does not explain my problem. In my case "main" is well defined.
class Test {
public static void main(String[] args) {
test1();
}
static void test1() {
Font f = new Font("SansSerif", Font.PLAIN, 70);
Glyph g = new Glyph(f, 'g');
System.out.println(g);
}
}

The problem is that the file isn't in a source folder. So for Eclipse, it's just a text file which (by coincidence) contains some Java code. But since the compiler never saw it, there is no .class file -> Eclipse can't run it.
Create a source folder (New... -> Source Folder) or move the file into an existing source folder in your project (they contain a little "package" symbol in the icon) and try again.

The name of the file and the name of the class should match. That is the reason, it's not able to recognize it. Please check the name again.

Haven't used eclipse in some time now as I use InteliJ but make sure you edit configurations and select your main file so Run can then execute your app.

Related

im trying to create a thread that sends and receives a message in java however im unsure on how to solve the error messages that are displayed [duplicate]

I have been working on an assignment for my class in programming. I am working with NetBeans. I finished my project and it worked fine. I am getting a message that says "No main class found" when I try to run it. Here is some of the code with the main:
package luisrp3;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
I posted this before but had a couple issues. i have fixed the others and now have just this one remaining. Any advice will be greatly appreciated.
Right click on your Project in the project explorer
Click on properties
Click on Run
Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
Click OK.
Run Project :)
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Also, for others out there with a slightly different problem where Netbeans will not find the class when you want when doing a browse from "main classes dialog window".
It could be that your main method does have the proper signature. In my case I forgot the args.
example:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above.
Args: You can name the argument anything you want, but most programmers choose "args" or "argv".
Read more here:
http://docs.oracle.com/javase/tutorial/getStarted/application/
When creating a new project - Maven - Java application in Netbeans
the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).
When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.
Steps that worked for me:
Create new project - Maven - Java application
(project created: mytest; package created: com.me.test)
Right-click package: com.me.test
New > Java Class > Named it 'Whatever' you want
Right-click package: com.me.test
New > Java Main Class > named it: 'Main' (must be 'Main')
Right click on Project mytest
Click on Properties
Click on Run > next to 'Main Class' text box: > Browse
You should see: com.me.test.Main
Select it and click "Select Main Class"
Hope this works for others as well.
The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)
I had the same problem in Eclipse, so maybe what I did to resolve it can help you.
In the project properties I had to set the launch configurations to the file that contains the main-method (I don't know why it wasn't set to the right file automatically).
In project properties, under the run tab, specify your main class.
Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.
If the advice to add the closing braces work, I suggest adding indentation to your code so every closing brace is on a spaced separately, i.e.:
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
// stuff
}
}
This just helps with readability.
If, on the other hand, you just forgot to copy the closing braces in your code, or the above suggestion doesn't work: open up the configuration and see if you can manually set the main class. I'm afraid I haven't used NetBeans much, so I can't help you with where that option is. My best guess is under "Run Configuration", or something like that.
Edit: See peeskillet's answer if adding closing braces doesn't work.
There could be a couple of things going wrong in this situation (assuming that you had code after your example and didn't just leave your code unbracketed).
First off, if you are running your entire project and not just the current file, make sure your project is the main project and the main class of the project is set to the correct file.
Otherwise, I have seen classmates with their code being fine but they still had this same problem. Sometimes, in Netbeans, a simple fix is to:
Copy your current code (or back it up in a different location)
Delete your current file
Create a new main class in your project (you can name it the old one)
Paste your code back in
If this doesn't work then try to clear the Netbeans cache, and if all else fails, then just do a clean un-installation and re-installation of Netbeans.
In the toolbar search for press the arrow and select Customize...
It will open project properties.In the categories select RUN.
Look for Main Class.
Clear all the Main Class character and type your class name.
Click on OK.
And run again.
The problem is solved.
If that is all your code, you forgot to close the main method.
Everything else looks good to me.
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
}}
Try that.
You need to add }} to the end of your code.
You need to rename your main class to Main, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main.
That's all.
import java.util.Scanner;
public class FarenheitToCelsius{
public static void main(String[]args){
Scanner input= new Scanner(System.in);
System.out.println("Enter Degree in Farenheit:");
double Farenheit=input.nextDouble();
//convert farenheit to celsius
double celsuis=(5.0/9)*(farenheit 32);
system.out.println("Farenheit"+farenheit+"is"+celsius+"in celsius")
{
I also experienced Netbeans complaining to me about "No main classes found". The issue was on a project I knew worked in the past, but failed when I tried it on another pc.
My specific failure reasons probably differ from the OP, but I'll still share what I learnt on the debugging journey, in-case these insights help anybody figure out their own unique issues relating to this topic.
What I learnt is that upon starting NetBeans, it should perform a step called "Scanning projects..."
Prior to this phase, you should notice that any .java file you have with a main() method within it will show up in the 'Projects' pane with its icon looking like this (no arrow):
After this scanning phase finishes, if a main() method was discovered within the file, that file's icon will change to this (with arrow):
So on my system, it appeared this "Scanning projects..." step was failing, and instead would be stuck on an "Opening Projects" step.
I also noticed a little red icon in the bottom-right corner which hinted at the issue ailing me:
Unexpected Exception
java.lang.ExceptionInInitializerError
Clicking on that link showed me more details of the error:
java.security.NoSuchAlgorithmException: MD5 MessageDigest not available
at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
at java.security.Security.getImpl(Security.java:695)
at java.security.MessageDigest.getInstance(MessageDigest.java:167)
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:113)
Caused: java.lang.RuntimeException
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:115)
Caused: java.lang.ExceptionInInitializerError
at org.netbeans.modules.parsing.lucene.LuceneIndex$DirCache.createFSDirectory(LuceneIndex.java:839)
That mention of "java.security" reminded me that I had fiddled with this machine's "java.security" file (to be specific, I was performing Salvador Valencia's steps from this thread, but did it incorrectly and broke "java.security" in the process :))
Once I repaired the damage I caused to my "java.security" file, NetBeans' "Scanning projects..." step started to work again, the little green arrows appeared on my files once more and I no longer got that "No main classes found" issue.
Had the same problem after opening a project that I had downloaded in NetBeans.
What worked for me is to right-click on the project in the Projects pane, then selecting Clean and Build from the drop-down menu.
After doing that I ran the project and it worked.
Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.
public static void main(String[] args)

Java ImageIO resource path

I have a Java program that runs fine in Eclipse - when I export an executable jar file it gives me an exception.
I know it is because I am giving it the wrong path but I do not know how to fix. I tried using getClass().getResourceaAsStream() (or sth. like that) but that did not work as well.
The code I am using at the moment is the following:
line 31:
BufferedImage image = ImageIO.read(new File("/src/res/loading.png"));
Okay, so I created a simple project, made a directory called res and threw some images into it
Before anyone points out that this not Eclipse, it shouldn't matter, we've already established that the Jar file contains the res directory and images, it's about replicating the structure
I then wrote a really simple example...
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
System.out.println(Test.class.getResource("/res/0.jpg"));
System.out.println(getClass().getResource("/res/0.jpg"));
}
}
which outputs...
file:/.../Test/build/classes/res/0.jpg
file:/.../Test/build/classes/res/0.jpg
No, before any points out the IDE's environment is different from the command lines, I also ran it from the command line...
java -jar Test.jar
jar:file:/.../Test/dist/Test.jar!/res/0.jpg
jar:file:/.../Test/dist/Test.jar!/res/0.jpg

Debugging java source file with multiple classes in eclipse: Source not found

I have similar problem to the one described here:
Eclipse and Java - source not found
I also looked at the following question: Eclipse java debugging: source not found but I could not see how that it applied to my case..
I have just started using Eclipse and its debugger.
Here is how to reproduce the problem using Eclipse 3.7.2 on Ubuntu 12.04 with java and javac version 7.
Start Eclipse and select workspace, e.g., "Test" in home folder.
Open java perspective
Open new java project with project name "Test"
Add a new java class "Test"
I now have the following screenshot:
Add the following code to the source file Test.java
set a breakpoint at new Test2(1)
open debug perspective
start debugging:
choose Step Into (F5)
Now the error is reported:
Any help on this issue is appreciated..
The class Launcher$AppClassLoader belongs to the JRE and is about to load your class. It has nothing to do with the source code of your own classes. If you step further you will reach your own class Test2. If you go to the end of your debug button bar (four buttons right to the “step into” button), there’s a “Use step filters” button. Activate it to avoid unnecessary steps into the JRE classes.
I believe you have to create an instance of Test before you can access the nested class Test2 in Test. Eclipse should have thrown an error in yours saying something like "No instance of Test2 is accessible" or something like that. Change your code to look like this and see if it works.
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Test mTest = new Test();
Test2 nTest = mTest.new Test2(1);
}
class Test2{
int i;
Test2(int i){
this.i = i;
}
}
}

Error: Could not find or load main class hello.world.HelloWorld

I am trying to run this project called "hello user". I am new to Java, so wrote a simple program that takes your name, and displays "Hello ". while Running it, I get the following error:
run:
Error: Could not find or load main class hello.world.HelloWorld
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
But when I run file HelloWorld.java, it does it fine
I am doing this on Netbeans IDE 7.2
Rather than the coding error, it could be related to IDE. Since the "Run File" runs okay, but 'Run Project" does not, I believe you have something to set up in IDE itself. Right click the project, and select "Set is as Main", now run the project. I am just giving it a guess, may not help you. But it worth a shot.If it does not help, please paste your code too.
Your class needs a public static void main(String[] args) function. And moreover I suspect that the error could be in the package.
If you want your class in <main_package>.<sub_package>, The directory structure is
- main_package
- sub_package
-HelloWorld.java
And be sure to write your class like this.
package main_package.sub_package;
public class HelloWorld {
public static void main(String[] args){
System.out.println("Hello " + args[o]);
}
}
This is all due to the naming convention in Java
You need to run the .class file containing the public static void main(String[] args) method..
Here, your HelloWorld.java file might contain a class with main() method.. So, you can run it..
This is because, execution of any Java program starts with the invocation of main().. JVM needs an entry point to your code.. Which is main().. If it doesn't find one.. It will not run..
So, make sure, whatever class file you are running, it should have main() method..
UPDATE :- And for the starting point, may be you can skip using packages.. Just go with plain Java class without packages..
This message can also appear in Eclipse (Juno 4.2.2 in my case) and I have found two potential causes for it.
In my cases:
1. a DTD was in error. I deleted the file and that solved the issue*.
2. having cleaned the project, an external Jar that I had built externally had been deleted as could be seen from Properties -> Java Build Path -> Libraries.*
*Having solved either of the above issues, it was necessary to restart Eclipse
if you are using intellij idea then just rebuilding (clean and build) project might solve your problem . because intellij might be still trying to load the old classes which are not there or changed
Make sure you call looks like below:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello user");
}
}
To run a Java class in stand alone mode, public static void main(String[] args) is the entry method, which is must.

Problems when trying to compile a Hello World with Eclipse

I'm having problems when trying to compile the following code:
I first tried compiling with this code:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
it works as it should. Now, if I try to replace the class name for any other name, it won't work anymore, as it seems to always look after HelloWorldApp. I made sure the file is being saved and so, I even reopened Eclipse. Still the same error. Maybe this is a common problem, with a small work-around?
Thanks
edit: I see what you guys mean, but why does it work when I have the file name as "Main.java" and a class name of "HelloWorldApp" ?
You need to rename your .java file to match the class name.
Eclipse will rename your .java file to match your class name automatically if you use its refactoring support. Right click on the class name, hover over Refactor, and select the Rename option. Now when you rename your class, Eclipse will automatically rename your .java file to match.
This is how Java works. Class must have the same name as the file. So the filename for the class MyApp, must be MyApp.java
Rename main as HelloWorldApp so that your app becomes HelloWorldApp.java.
When changing the name of your class use the REFACTOR option - If you try to edit the name manually yourself the Eclipse Project loses track of your objects.

Categories

Resources