Getting "Exception in thread "main" java.lang.NoSuchMethodError: main"? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Exception in thread “main” java.lang.NoSuchMethodError: main
I am fairly new to Java, and I am unable to figure out why I am getting NoSuchMethodError: main when I execute the following code. I am not sure what does the NoSuchMethodError is pertaining to. It looks like I have everything right. Please help me out here. Thanks a lot.
public class ThreadExample1 extends Thread
{
static String[] msg = {"Java", "programming", "is", "the", "best"};
public ThreadExample1(String id)
{
super(id);
}
#Override
public void run()
{
try
{
Output.displayList(getName(), msg);
}
catch (InterruptedException ex)
{
}
}
}
class Output
{
public static void displayList(String name, String list[]) throws InterruptedException
{
for (int i = 0; i < list.length; i++)
{
Thread.currentThread().sleep((long) (3000 * Math.random()));
System.out.println(name + list[i]);
}
}
public static void main(String[] args)
{
ThreadExample1 thread1 = new ThreadExample1("thread1: ");
ThreadExample1 thread2 = new ThreadExample1("thread2: ");
thread1.start();
thread2.start();
boolean t1IsAlive = true;
boolean t2IsAlive = true;
do
{
if (t1IsAlive && !thread1.isAlive())
{
t1IsAlive = false;
System.out.println("t1 is dead.");
}
if (t2IsAlive && !thread2.isAlive())
{
t2IsAlive = false;
System.out.println("t2 is dead.");
}
}while (t1IsAlive || t2IsAlive);
}
}

I don't have any problem compiling and executing the above code ... Keep in mind that when you want to execute it , you need to use this command line :
java Output
and NOT :
java ThreadExample1
because the main method is within the Output calss and not in ThreadExample1 ...

Save the file as ThreadExample1.java and compile. After that you should run Output class but not the ThreadExample1 class. This is because you have added your main method inside Output class. But since you have made your ThreadExample1.java class public you have to save and compile using that name(javac ThreadExample1.java). After that java Output

Take a look at code-snippet the main() method is in Output class.
Use following command line to launch the Output.main() method:
c:\>java Output

When you do compile a java program you do need to give the file name after javac.
like javac MyProgram.java
and when you do run it using java then you need to mention the name of the class that is having "public static void main(String args[])" method.
Say I have two classes in MyProgram.java : Class First and Class Second
and I have "public static void main(String args[])" in Class Second then I will do the following :
javac MyProgram.java
java Second

Related

I/O using windowbuilder in eclipse for a java application

I've never used java windowbuilder before, however I'm trying to test it with my program which performs operations on sets. It's a Gradle project. I wrote all classes in the default package (I knew that it's discouraged just when I was finished). The program reads a line of operations on sets, parses it and prints the result and keeps doing that while there is a new line input from the user.
I'm trying to make a simple GUI for this program using windowbuilder but I can't figure out how to run the main class in the windowbuilder class and make it take input from a jtextfield and prints output.
My main looks like this:
public static void main(String[] argv) {
new Main().start();
}
private void start() {
hmap = new HashMap<IdentifierInterface, SetInterface<BigInteger>>();
Scanner in = new Scanner(System.in);
// While there is input, read line and parse it.
while (in.hasNextLine()) {
try {
String statement = in.nextLine();
if (statement.trim().isEmpty()) {
System.out.println("error, no statement");
} else {
Scanner statementScanner = new Scanner(statement);
readStatement(statementScanner);
}
} catch (APException e) {
System.out.printf("%s\n", e.getMessage());
}
}
}
I made a new windowbuilder class, with the buttons and text fields, but I got stuck on how to run my main inside the windowbuilder. Your help is appreciated. Thanks in advance.
Eclipse RCP applications are OSGi plug-ins; they do not have a main() method.
Instead your Main class should look like this:
package com.myplugin;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Main implements BundleActivator {
#Override
public void start(BundleContext bundleContext) throws Exception {
// Copy your start logic here
}
}
Then edit META-INF/MANIFEST.MF file and set for example
Bundle-Activator: com.myplugin.Main
This makes your Main class the activator of the plug-in: start() will be invoked at load.

voce - Simple Java code not working

I recently installed Voce and am using it in my Java application. In Eclipse, I added the JAR files in voce-0.9.1/voce-0.9.1/lib to the libraries in my Java Build Path. From the documentation, I figured that this code should work:
import voce.SpeechSynthesizer;
public class Test
{
public static void main(String[] args)
{
// System.out.println("Speaking");
SpeechSynthesizer speaker = new SpeechSynthesizer("speaker");
speaker.synthesize("hello");
// System.out.println("Spoken");
speaker.destroy();
}
}
When I uncomment the output statements, the program outputs "Speaking", then almost immediately outputs "Spoken" without having made a sound. My volume is turned up. Does synthesize() speak the string or have I forgotten some initialization? And can you give me some code that should work?
Answer
Here is the code that worked (I used the static methods in SpeechInterface instead of a SpeechSynthesizer object):
public class Test
{
public static void main(String[] args)
{
voce.SpeechInterface.init("../../../lib", true, false, "", "");
System.out.println("Speaking");
voce.SpeechInterface.synthesize("hello");
System.out.println("Spoken");
try { Thread.sleep(1000); } catch(Exception ex) {}
voce.SpeechInterface.destroy();
}
}

PyLucene JCC: implement a Java interface in python and receive Java thread callbacks through it

I'm playing around with my new toy, JCC 2.21, and am having trouble implementing callbacks in a python script. I have wrapped the following simple Java thread API and am calling it from python 2.7 (CPython), but when I call the JccTest.addJccTestListener(JccTestListener) method, the JVM reports a null argument.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class JccTest implements Runnable {
private final Object listenersLock = new Object();
private final List<JccTestListener> listeners = new ArrayList<JccTestListener>();
private final AtomicBoolean running = new AtomicBoolean(false);
private final AtomicBoolean finished = new AtomicBoolean(false);
public void start() {
if (running.compareAndSet(false, true)) {
new Thread(this).start();
}
}
public void stop() {
finished.set(true);
}
public void addJccTestListener(JccTestListener l) {
if (l == null) {
throw new IllegalArgumentException("argument must be non-null");
}
synchronized (listenersLock) {
listeners.add(l);
}
}
public void removeJccTestListener(JccTestListener l) {
synchronized (listenersLock) {
listeners.remove(l);
}
}
#Override
public void run() {
System.out.println("Start");
while (!finished.get()) {
System.out.println("Notifiying listeners");
synchronized (listenersLock) {
for (JccTestListener l : listeners) {
System.out.println("Notifiying " + String.valueOf(l));
l.message("I'm giving you a message!");
}
}
System.out.println("Sleeping");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
continue;
}
}
running.set(false);
System.out.println("Stop");
}
public static void main(String[] args) throws InterruptedException {
JccTest test = new JccTest();
test.addJccTestListener(new JccTestListener() {
#Override
public void message(String msg) {
// called from another thread
System.out.println(msg);
}
});
test.start();
Thread.sleep(10000);
test.stop();
}
}
public interface JccTestListener {
public void message(String msg);
}
Generated wrapper with:
python -m jcc --jar jcc-test.jar --python jcc_test --build --install
And then executed this script (equivalent to the main method of JccTest):
import jcc_test
import time, sys
jcc_test.initVM(jcc_test.CLASSPATH)
test = jcc_test.JccTest()
class MyListener(jcc_test.JccTestListener):
def __init__(self):
pass
def message(self, msg):
print msg
test.addJccTestListener(MyListener())
test.start()
time.sleep(10)
test.stop()
sys.exit(0)
Which results in:
"python.exe" jcc_test_test.py
Traceback (most recent call last):
File "jcc_test_test.py", line 16, in <module>
test.addJccTestListener(MyListener())
jcc_test.JavaError: java.lang.IllegalArgumentException: argument must be non-null
Java stacktrace:
java.lang.IllegalArgumentException: argument must be non-null
at com.example.jcc.JccTest.addJccTestListener(JccTest.java:32)
Besides the null listener instance, is doing something like this even possible with CPython? I've read that in its implementation only one thread may execute the python script at a time, which might (?) be a problem for me. Doing something like this with Jython was trivial.
I'm rather new to python so please be gentle.
Figured it out. You need to define a pythonic extension for a java class to make this work. The detailed procedure is described in JCC documentation (Writing Java class extensions in Python) and is rather simple.
First, code a class that implements your interface and add some magic markers that are recognized by JCC and affect what the wrapper generator will generate.
public class JccTestListenerImpl implements JccTestListener {
// jcc specific
private long pythonObject;
public JccTestListenerImpl() {}
#Override
public void message(String msg) {
messageImpl(msg);
}
// jcc specific
public void pythonExtension(long pythonObject) {
this.pythonObject = pythonObject;
}
// jcc specific
public long pythonExtension() {
return this.pythonObject;
}
// jcc specific
#Override
public void finalize() throws Throwable {
pythonDecRef();
}
// jcc specific
public native void pythonDecRef();
public native void messageImpl(String msg);
}
The markers are denoted by my comments and must appear verbatim in any class that is to be extended in python. My implementation delegates the interface method to a native implementation method, which will be extended in python.
Then generate the wrapper as usual:
python -m jcc --jar jcc-test.jar --python jcc_test --build --install
And finally make a python extension for the new class:
import jcc_test
import time, sys
jvm = jcc_test.initVM(jcc_test.CLASSPATH)
test = jcc_test.JccTest()
class MyListener(jcc_test.JccTestListenerImpl):
## if you define a constructor here make sure to invoke super constructor
#def __init__(self):
# super(MyListener, self).__init__()
# pass
def messageImpl(self, msg):
print msg
listener = MyListener()
test.addJccTestListener(listener)
test.start()
time.sleep(10)
test.stop()
sys.exit(0)
This now works as expected with callbacks coming in.
"python.exe" jcc_test_test.py
Start
Notifiying listeners
Notifiying com.example.jcc.JccTestListenerImpl#4b67cf4d
I'm giving you a message!
Sleeping
Notifiying listeners
Notifiying com.example.jcc.JccTestListenerImpl#4b67cf4d
I'm giving you a message!
Sleeping
Process finished with exit code 0

What am I doing wrong - can't instantiate object from Main (Custom class)

Hands up, I'm struggling with a programming question for M257 at OU, its formative and carries no marks and is due in a few days. I can't call the constructor from the test class and have struggled for several hours to no avail, the class compiles in Netbeans 6.91 fine but the constructor won't create the object. What am I doing wrong?
I had no problem with first question but am totally stuck here, obviously missing something significant - guidance please. The idea is to pass in the name of the file to the class, I can do the rest once I know the file is open and scanner initialised.
===============
/**
* Title: WordCounter class
* Description: M257 TMA01, Q2 - word counter class as described in instructions
* #author Andrew Broxholme
*/
package tma01q2;
import java.io.*;
import java.util.*;
public class WordCounter
{
//Class instance variables
public static int totalWords;
public static int totalEven;
public static int totalOdd;
public static int totalLetters;
private Scanner fileScanner;
String sourceFile;
String line; //The lines of the text file
//Single argument constructor, accepts source filename
public boolean WordCounter(String fileToRead)
{
sourceFile = fileToRead;
try
{
openRead();
while (fileScanner.hasNext())
{
// Process each line of the text file
line = fileScanner.nextLine();
System.out.println(line);
// countWords();
}
return true;
}
catch (Exception exp)
{
return false;
}
finally
{
fileScanner.close();
}
}
//openRead, opens the file and processes each line of the file until finished
private boolean openRead() throws IOException
{
try
{
fileScanner = new Scanner(sourceFile);
return true;
}
catch (Exception exp)
{
return false;
}
}
// More methods to be added
}
/*
* TestWordCounter.
* Description: Tests the WordCounter class as per TMA01q2 instructions
* #author Andrew Broxholme
* V1.0 30th April 2011
*/
package tma01q2;
public class TestWordCounter
{
//Create a WordCounter to process the specified text file.
public static void main(String[] args)
{
String testFile = "haiku.txt";
WordCounter fileStats = new WordCounter(testFile);
}
}
When I try to comiple this is what it passes back.
Compiling 1 source file to C:\M257\TMA01\TMA01Q2\build\classes
C:\M257\TMA01\TMA01Q2\src\tma01q2\TestWordCounter.java:18: cannot find symbol
symbol : constructor WordCounter(java.lang.String)
location: class tma01q2.WordCounter
WordCounter fileStats = new WordCounter(testFile);
1 error
C:\M257\TMA01\TMA01Q2\nbproject\build-impl.xml:246: The following error occurred while executing this line:
C:\M257\TMA01\TMA01Q2\nbproject\build-impl.xml:113: Compile failed; see the compiler error output for details.
I haven't given up on this and will update question if I find the answer first.
8th May 2011: The answers were helpful but in the end although in the end I gave up on this question as the further I got I realised I just didn't know enough about how subclasses inherit from superclasses and need to try some simpler (and to me more meaningful) examples to deepen my understanding. The problem though was that NetBeans is too good at suggesting what you need without telling you exactly why its doing what it is doing, fine if your an experienced java developer, but not so good if your starting out.
I'm already started (i.e read the brief) for TMA02 and will give myself a full two months, much more sensible one thinks!
This is not a constructor. Remove the boolean as return type - constructors don't have return types. So:
public WordCounter(String fileToRead)
instead of
public boolean WordCounter(String fileToRead)
And that's what the error tells you - the compiler cannot find a constructor with that name.
See: constructors
the signature of the constructor is wrong.
public WordCounter(String fileToRead)
{
sourceFile = fileToRead;
try
{
openRead();
while (fileScanner.hasNext())
{
// Process each line of the text file
line = fileScanner.nextLine();
System.out.println(line);
// countWords();
}
return true;
}
catch (Exception exp)
{
return false;
}
finally
{
fileScanner.close();
}
}
use constructor like this. Replace the signature of constructor to
public WordCounter(String fileToRead)

Get the method name and it's contained parameters by parsing the exception

When I received an exception such as IOException or RunTimeException, I can only know the line number in the class.
First of my question. Is it possible to retrieve the method name through exception?
Second, is it possible to retrieve the method and the parameter of this method by line number?
p.s. I need to know the exact method name and its parameters, because I want to distinguish the overloading methods. To distinguish overloading methods, all that I know is to determine its parameters.
try{
//your code here}
catch(Exception e){
for (StackTraceElement st : e.getStackTrace())
{
System.out.println("Class: " + st.getClassName() + " Method : "
+ st.getMethodName() + " line : " + st.getLineNumber());
}
}
as you can see in the code above, you can get the stackTrace and loop over it to get all the method names and line numbers, refer to this for more info http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html
If you look at the stacktrace you can know in which line the error occurred.
When using an overriden method you get the exact class name, source file and line number, you just have to know how to read it.
From that page:
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9) //<--- HERE!!!!
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)
This says, the problem occurred in line 9 of file MyClass.java in the method mash, which was in turn invoked by the method crunch at line 6 of the same file which was invoked by main in line 3 of the same file.
Heres the source code:
class MyClass {
public static void main(String[] args) {
crunch(null); // line 3
}
static void crunch(int[] a) {
mash(a); // line 6
}
static void mash(int[] b) {
System.out.println(b[0]);//line 9, method mash.
}
}
Basically you just have to ... well read it!
Stacktraces are a bit hard to grasp the first time, but later they become a very powerful tool.
I hope this helps.
pass it the exception and it will print the parameter types of the methods along with the exception
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
new Main().run();
}
public void run(){
try
{
new Car().run(60, "Casino");
}
catch (Exception e)
{
detailedException(e);
}
try
{
new Engine().run(10);
}
catch (Exception e)
{
detailedException(e);
}
}
public void detailedException(Exception e)
{
try
{
StringBuilder buffer = new StringBuilder(e.getClass().getName()).append(" \"").append(e.getMessage()).append("\"\n");
for (var trace: e.getStackTrace())
{
buffer.append("\tat ").append(trace.getClassName()).append(".").append(trace.getMethodName()).append("(").append(trace.getFileName()).append(":").append(trace.getLineNumber()).append(")[");
Class<?> clazz = Class.forName(trace.getClassName());
ArrayList<Method> methods = new ArrayList<>(Arrays.asList(clazz.getMethods()));
methods.removeIf(m -> !m.getName().equals(trace.getMethodName()));
Method method = methods.get(0);
for (var param: method.getParameters())
{
buffer.append(param.getName()).append(":").append(param.getParameterizedType().getTypeName()).append(", ");
}
buffer.append("]->").append(method.getGenericReturnType().getTypeName()).append("\n");
}
System.err.println(buffer);
}
catch (Exception parseFailed){
e.printStackTrace();
}
}
}
class Car extends Engine
{
public void run(int when, String where) throws Exception
{
super.run(25);
}
}
class Engine
{
public String run(int For) throws Exception
{
throw new Exception("need more fuel");
}
}

Categories

Resources