My problem is not the connection. I have ubuntu 23.04 and I installed R (sudo apt install r-base-core) then I installed the package rserve in R (sudo -i R) and ‘install.packages("Rserve")’. Then I raise and R server (R CMD Rserve) after I download two jar necessary files: REngine.jar and RserveEngine.jar . Since here well but, my Java’s program doesn’t work well and I don’t know why.
When I compile it in the folder with the two jar’s files and my Rmatrix.java with javac -cp ./:REngine.jar:RserveEngine.jar Rmatrix.java
I am getting the following error message:
unreported exception RserveException; must be caught or declared to be thrown
repeatedly (several for REXPMismatchException, several for RserveException, and several for REngineException, all with the same sentence to which I have referred before ). I think the problem is the program structure:
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
import java.util.*;
import java.io.IOException;
public class Rmatrix {
public static void main(String [] args) {
RConnection con = new RConnection();
con.eval("d = rnorm(10)");
double[] d = con.eval("d").asDoubles();
System.out.println(d);
double [] x = {1,2,3,4,5};
double[] y = {1,2,3,4,5};
con.assign("x", x);
con.assign("y", y);
con.eval("z = x + y");
double[] z = con.eval("z").asDoubles();
System.out.println(z);
con.close();
}
}
I hope someone tell me how to fix it. Perhaps adding some piece of code like ‘throws IOException’ in the name of the class or ‘try{ }catch(IOException e){e.printStackTrace();}’ into the program’s code. I don’t know who to do it.
2
Answers
This program run perfectly:
And run with: 'java -cp ./:REngine.jar:RserveEngine.jar Rmatrix'
Thank's.
As the error message says, you have to handle the checked exceptions in your code. RserveException, REXPMismatchException, and REngineException are all checked exceptions, so they have to be either caught or declared thrown. The simplest solution is then (RserveException is a subclass of REngineException):
Of course, a more sensible approach is to catch and handle the exceptions: