I'm coding a Library program for my classroom, but I ran into an error quite immediately after compiling. The challenge for this program is that I need to use 3 files, only one of which (libraryRunner) actually has a Main in it. I'm trying to get both of the other method files (libraryCard and libraryBooks respectively) to work together.
I used Booleans before, and switched to Ints to see if that would fix it, but i get the same error. What's weird is that the program seems to compile, but the program just exits after the previously mentioned error.
Library Runner :
import java.util.Scanner;
public class libraryRunner
{
public static void main (String args[])
{
libraryCard Joseph = new libraryCard();
Joseph.whichBook("Sing");
}
}
What i'm using in Library Card :
...
public static String whichBook(String c)
{
if(libraryBooks.c == 1)
{
return("Sorry, it's already been checked out.");
}
else
{
return("Here's your book, " + c + "!");
}
}
}
What i'm using in Library Books:
public class libraryBooks
{
private static int hasBeenCheckedOut;
public libraryBooks()
{
libraryBooks.Sing(0);
}
public static int Sing(int c)
{
hasBeenCheckedOut = c;
return(hasBeenCheckedOut);
}
...
From what even my teacher tells me, the program should in theory compile and run, telling the user that the book "Sing" is now theirs. But I only get this error :
----jGRASP exec: java libraryRunner
Exception in thread "main" java.lang.NoSuchMethodError: libraryCard.whichBook(Ljava/lang/String;)Ljava/lang/String;
at libraryRunner.main(libraryRunner.java:8)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Related
I have a simple java class as shown below:
public class Add2Numbers
{
public static void main(String[] args)
{
int num1=2, num2=4, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
I compile the class and run in matlab using:
obj = Add2Numbers;
javaMethod('main', o,"");
and I get the output: Sum of these numbers: 6 which is, of course, correct.
Next I change the code in my text editor (e.g. set num1=4) compile, execute the clear statements below:
clear all
clear java
clear import
clear CLASSES
clear ALL
clear
then run again:
obj = Add2Numbers;
javaMethod('main', o,"");
But the calculation result remains the same as before. If I close and restart MATLAB the modified java class runs correctly. So how on earth do I clear a java class without having to close MATLAB and restart it?
set
I am trying to find the square of a number using the scanner method but keep getting a
stackflow error. I am new to programming will be glad if someone helps me out.
My code is as below
import java.util.Scanner;
interface Number {
int findSqr(int i); // Returns the square of n
}
//a class A which implements the interface Number.
class A implements Number {
public int findSqr(int i) {
return findSqr(i);
}
}
public class Question5_1{
public static void main (String[] args){
A a = new A(); // an object of class A
// Reading a number from the keyboard
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.print(a.findSqr(i));
}
}
Fix the line which invokes the function recursively return findSqr(i) with return i * i as follows --
public int findSqr(int i) {
return i * i;
}
What you did there is an infinite recursion. The bit where it says
public int findScr(int i) {
return findSqr(i)
}
essentially calls the very same method an infinite number of times in the return statement.
What happens is, that you execute the method, and it tries to return an integer. What you wrote though is a return statement that "returns" another call of the same method, so it gets executed again. Then the whole thing starts over again, so you get a StackOverflow.
Since there is no other code present, I have no idea what you are actually trying to do, but the return findSqr(i) line is what causes the problem.
Initially, recursion may be a rather complicated subject to really wrap you head around, I suggest you either avoid it for now (although it enables you to solve many problems in a really elegant way) or try to understand it a bit better maybe. I'd suggest the Wikipedia article about recursion, although it gets complicated quite fast, or any other tutorial on it, just look it up on Google.
I'm working on a program that uses JavaFx to display icons in a list.
I've made a static class used to look up specific ids from a txt document. Originally, the static block would add the id and name of an item defined on each line, but since these issues arose, I've tried to find the source of the issue.
Instead, I've just gone through the text file's content in the static block and have printed it out to the console.
This is my code for reference:
public class ItemIds {
public static int UNDEFINED_ID = -1;
private static HashMap<String, Integer> items;
static {
items = new HashMap<String, Integer>();
System.out.println(new File("res/ids/item ids.txt").exists());
try {
//should print out every line in the text file
Files.lines(Paths.get("res/ids/item ids.txt")).forEach(s -> {
System.out.println(s);
});
} catch (IOException e) {
System.out.println("Unable to read specified file.");
e.printStackTrace();
}
}
public static int getId(final String name) {
final Integer id = items.get(name);
return id != null ? id : UNDEFINED_ID;
}
}
However, what I do get when this static class is initialized and the static block is invoked is quite odd. It lists every single line without error until it gets to line 10691, where it throws "Exception in thread "JavaFX Application Thread" java.lang.ExceptionInInitializerError".
What makes this particularly weird, however, is that when I work with a smaller text document (with less entries), everything seems to work fine. Since the file is comprised of almost 14000 lines, I have to delete ~4000 lines for it to be able to work.
Any ideas on why it would be doing this? Any feedback is appreciated - thank you
I am unable to reproduce this error. I have created a file with 18K lines and you program just works fine with that. So, definitely consider reviewing your file and also the stack trace.
Now coming back to your exception ExceptionInInitializerError, the following is a possible:
ExceptionInInitializerError signals that an unexpected exception has occurred in a static initializer. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.
class ItemIds
{
static
{
// if something does wrong -> ExceptionInInitializerError
}
}
Because static variables are initialized in static blocks there is a potential for introducing errors too. An example:
class ItemIds
{
static int v = D.foo();
}
=>
class ItemIds
{
static int v;
static
{
v = D.foo();
}
}
So if foo() goes crazy then you can get a ExceptionInInitializerError.
Have you presented your complete code in static block?
I would like to calling my own Java program from Matlab.
This is my java program:
public class TestArgu{
public static void main(String[] args){
System.out.println("Test passing arguments!");
}
public void addNumber(int aNumber){
ansNumber = aNumber+5;
chk = aNumber;
System.out.println("input number = " + chk + ".\n");
System.out.println("ans = " + ansNumber + ".\n");
}
public int ansChk(){
return ansNumber;
}
private int ansNumber;
private int chk;
}
I did step by step from this link
http://www.mathworks.nl/support/solutions/en/data/1-URS0E/?...1...
but it is not working with my program.
I'm running Matlab program from the Server computer.
So I cannot edit the classpath.txt.
How to fix this problem?
First, delete the main function from your class. Then add the line
package mypackage.release;
before your class definition. Then compile it using the command
javac -verbose -cp /home/javaclasses -d /home/javaclasses /home/javasource/TestArgu.java
In matlab type
javaaddpath('/home/javaclasses');
clear java;
import mypackage.release.*;
test=TestArgu;
test.addNumber(6);
test.ansChk();
Remember that everytime you make changes and compile the java class, you must call clear java in matlab before the changes are available. This also has the unfortunate side effect of clearing all the variables in your workspace so make sure you don't have anything important to save before calling it.
I am really new to java (started learning 2 days ago). Sorry if this is a stupid question. I am trying to learn how to use rt.exec & similar methods so I tried to make a very simple program which runs calc.exe. This is the code:
public class main {
{
try {
Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec("calc.exe") ;
}
catch(Exception exc){/*handle exception*/}
}
}
I get the error " The value of local variable p is not used".
And if I try to compile this is what I get:
I think it's easy to fix but I don't know how. Would be nice if someone helped.
Well, the error "The value of local variable p is not used.", Is not actually an error. It's your IDE (Eclipse), warning you that you aren't actually reading that variable, so you aren't receiving any input from it.
And the other problem with your class is, you don't have a main method. Like this,
public class main {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec("calc.exe") ;
} catch(Exception exc){
/*handle exception*/
}
}
}
And by the way, you should always start a class name with a captial letter. So public class main, should actually be public class Main
You get that error because you don't have the main method that is used to start the java program:
public class main {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec("calc.exe") ; // here, eclipse is WARINING(so you can ignore it) you that that the variable p is never used(it's just a warning)
} catch(Exception exc) {
/*handle exception*/
// never do this, always put at least a System.out.println("some error here" + e); so you don't ignore a potential exception
}
}
I believe what you have is not an error but a warning; eclipse (and other IDEs/compilers) will tell you that, although you assigned a value to the variable p, you did not use it anywhere. It tells you this because this is sometimes an error; mostly when you assign a value to a variable, you later use that variable in some way.
You can eliminate the error by changing that particular statement to just
rt.exec("calc.exe")
since you are not required to assign a value from the call to exec.
There is no such thing as a stupid qiestion(only misplaced ones, in the worst case).
The "Editor does not contain a main type" refers to the fact that you have not defined a main method. All java programs require a main method, as such:
public static void main(String [] args){
<code>
}
This is where you must place your code.
The "Value not used" is just a warning; it tells you that your variable p only exists within the try-block. You can declare your p-variable before the try - that way, you can use it outside the try-scope(the scope of a variable refers to where it exists, in this case, only inside the try-block).
If you want to use your p, this is what you're after:
public class Main {
public static void main(String[] args) {
Process p;
try {
Runtime rt = Runtime.getRuntime();
p = rt.exec("calc.exe");
} catch(Exception exc) {/*handle exception*/}
}
}
[EDIT]: Note that it is part of the java coding convention to use Capital letters for the first letter of a class, e.g. Main.java(not main.java)
The use of the variable is not in issue here. That error appears because JVM needs a method with the signature to know where to start execution.
public static void main( String args[] ){ //TODO: Stuff here }
Introduce a method with this signature in your class, and it shall clear that error.
Alternatively, you may embed your code in a static block as below - but this method is not to be recommended.
static {
// TODO: Your code here
}
Error "The value of local variable p is not used" due to the fact that nowhere in the code, you do not use the variable p.
To remove the error - it is necessary to remove the variable "p".
To run the calculator, you must use the code:
public class MainClass {
public static void main(String args[]) throws IOException {
Runtime.getRuntime().exec("cmd /c calc.exe");
}
}
This and all other comments translated by Google Translate
you are not using main how can you compile please use main method.
Ans second one is use p local variable in your method.other wise declare p variable starting of method.