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)
Related
I Tried putting an image onto a JButton. After wrote down the path to the image, ran the Program,then image was not on the Button. Code Sample below:
public static JButton start = new JButton(new ImageIcon("resources//img//menu//Start_Game.png"));
The "resources" folder is in the "src" folder. Here is the Hirarchy in Eclipse
After I double checked I spelled everything right, I put in an other path.
public static JButton start = new JButton(new ImageIcon(System.getProperty("user.home") + "//Tindir//Hauptmenue//Start_Game.png"));
Suddenly it worked. It is obvious that the first path was not correct.
Question If there is a way to input a path to an Image in the same Project-Folder as the Code?
Yes, but not that way - those arguments are filenames, and java code is not deployed as a sack of files. It's deployed as a jar file. An entry inside a jar file does not count and can never be used with this API.
So, don't use this call. Use the other one, that takes a URL, because you certainly can represent either a file, or an entry within a jarfile, as one of those:
MyClass.class.getResource("Start_Game.png")
That is what you put instead of "resources/etc/Start_Game.png" in that code. This looks for a resource named Start_Game.png in the exact same place that MyApp.class is found, even if that is found inside a jar file, loaded out of a DB, live-streamed from the internet - whatever. You're using the same mechanism.
If your Start-Game file is somewhere else, start with a /. It seems like you want /img/menu/Start_Game.png here.
This trick is an easy way to get an idea of what you're doing:
class MyClass {
public static void main(String[] args) {
System.out.println(MyClass.class.getResource("MyClass.class"));
}
}
and you'll figure it out with that output.
I am having the following problem:
I have an Enum that was originally declared with 5 elements.
public enum GraphFormat {
DOT,
GML,
PUML,
JSON,
NEO4J,
TEXT {
#Override
public String getFileExtension() {
return ".txt";
}
};
Now I need to add an additional element to it (NEO4J). When I run my code or try to debug it I am getting an exception because the value can't be found in the enum.
I am using IntelliJ as my IDE, and have cleaned the cache, force a rebuild, etc.. and nothing happens. When I look at the .class file created on my target folder, it also has the new element.
Any ideas on what could be causing this issue ?
I found my problem and want to share here what was causing it. My code was actually for a Maven plug-in which I was pointing to another project of mine to run it as a goal. However the pom.xml of my target test project was pointing to the original version of the plug-in instead of the one I am working on, and that version of course is outdated and does not include the new value. Thank you.
I have the following program which adds a method to itself when run. But I have to refresh it every time using the F5 button or the refresh option.
Is there a way I could code the refresh in the program itself so that it refreshes itself after the modification? The project I am working on is a Java application and not an eclipse plugin so as far as I know the refreshLocal() method can't be used.
public class Demo {
public static void main(String[] args) throws IOException, CoreException {
File file = new File("/home/kishan/workspace/Roast/src/Demo.java");
if (file.exists()) {
JavaClassSource javaClass = Roaster.parse(JavaClassSource.class,
file);
javaClass.addMethod().setPublic().setStatic(true)
.setName("newMethod").setReturnTypeVoid()
.setBody("System.out.println(\"newMethod created\");")
.addParameter("String[]", "stringArray");
FileWriter writer = new FileWriter(file);
writer.write(javaClass.toString());
writer.flush();
writer.close();
}
}
}
I have tried using the refreshLocal() method defined in the eclipse JDT but since my project is a Java application the ResourcePlugin.getWorkspace() method does not work giving me a "workspace closed" error. Any suggestion is appreciated.
You see, eclipse runs your Java class within its own dedicated JVM. Thus there is no direct programmatic way of enforcing a refresh within eclipse.
You could check this older question; maybe that could lead to a reasonable workarounds.
On the other hand you might step back and ask yourself why exactly you want to achieve that. Your workflow simply doesn't make much sense when looking at it; as in: when generating code that way, shouldn't that generated code better go in its own specific place?
If you intend to "generate" code frequently to then continue to use it in eclipse; well, that somehow smells like a strange idea.
Eclipse has "Refresh using native hooks or polling" which might might help.
You can find it under Window > Prefrences > General > Workspace.
See On Eclipse, what does "Preferences -> General -> Workspace -> Refresh using native hooks or polling" do?
I'm writing an Eclipse plugin with a custom launch configuration, i.e. a launch() method inside a subclass of LaunchConfigurationDelegate. This method essentially just calls Runtime.exec(), but when I write to System.out from within launch() it goes to the console of the Eclipse instance which is debugging the plugin, rather than to the console of the plugin instance itself. I've analysed the ILaunchConfiguration and ILaunch arguments to the method but cannot find anywhere that they specify any output/error streams I can write to.
As is recommended in the tutorials, I have 2 separate plugins running together; one which handles the UI stuff (LaunchConfigurationTab,LaunchConfigurationTabGroup,LaunchShortcut,) and the other which contains the LaunchConfigurationDelegate itself.
I created a console in my UI plugin using this code, and I can write to it fine from within the UI code. But I cannot figure out how to direct output generated in my non-UI plugin to the console created in my UI plugin.
I've read this post and this one, but they do not specify how to "get ahold" of the output which is generated within the launch() method in the first place.
Any pointers would be really welcome, I am stuck!
Well I finally managed to get something working as follows:
In my LaunchConfigurationDelegate I introduced the following static method:
public static void setConsole(PrintStream ps) {
System.setOut(ps);
System.setErr(ps);
}
Then when creating my console in my UI plugin's PerspectiveFactory I call it as follows:
private void createConsole() {
console = new MessageConsole("My Console", null);
console.activate();
ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[]{ console });
MessageConsoleStream stream = console.newMessageStream();
MyLaunchConfigurationDelegate.setConsole(new PrintStream(stream));
}
This works, except everytime I close down Eclipse and restart it the console disappears. However when I reset my perspective, the console appears again. So obviously I need that code to be called on startup, not in the PerspectiveFactory itself.
Hope this helps someone.. and if anybody has some input for this last problem (or about my approach in general) please do comment!
How can I setup Eclipse to stop at the point an exception occurred.
I have an Eclipse breakpoint setup to break on an exception. In the code example below, the problem I'm having is Eclipse tries to open the Integer source code. Is there any way to just have debugger break at the point shown in my code example? If I move down the stack trace, I will get to this line, it'd be nice if there's a way to do this without the "Source not found" window coming up.
This can be done in Visual Studio, so it's driving me crazy not being able to find a way to do this in Eclipse.
package com.test;
public class QuickTest
{
public static void main(String[] args)
{
try
{
test();
}
catch(NumberFormatException e)
{
System.out.println(e.getMessage());
}
}
private static void test()
{
String str = "notAnumber";
Integer.parseInt(str);//<----I want debugger to stop here
}
}
I'm not sure how else to get there, but I just do:
Window -> Show View -> Breakpoints
And in that tab there is a "J!" that lets you set breakpoints on exceptions.
Preferences -> Java -> Debug -> Step Filtering
Choose packages you want to filter out when debugging (java.*, sun.*, etc)
On debug make sure the little step filtering arrow is selected.
This should do the trick.
Can't you just set a breakpoint on the Integer.parseInt(str) line?
If you point your Eclipse project at using a JDK instead of a JRE it should pick up the source code for all of the platform classes (Integer etc).
The Debug view will show the entire stack of the current execution. You need to select the line you want to see. It will be same as you had a breakpoint there, you can see all the variables etc.