I want to use R to input a parameter into Java, for example "1000". Then method of StringToNum process and output its return to R,namely 1000. Seems it is the work of .jcall(), but I dont know how to do with its parameters.As I dont know Java, Could you please help me?
Thank you very much!
Java code
package com.mingdong.rcalljava.test;
import java.io.PrintStream;
public class StringToNum
{
private String inputString = null;
public StringToNum(String inputString)
{
this.inputString = inputString;
}
public StringToNum()
{
}
public int convertStringToInt()
{
if (this.inputString == null) {
this.inputString = "100";
}
return Integer.valueOf(this.inputString).intValue();
}
public static void main(String[] args)
{
StringToNum stringToNum = new StringToNum();
int num = stringToNum.convertStringToInt();
System.out.println("num:" + num);
}
}
R code
library(rJava)
.jinit()
.jinit('D:/Eclipse/dailyjob/javaProject/TestRCallJava.jar')
## .jaddClassPath("D:\\Eclipse\\dailyjob\\javaProject\\TestRCallJava.jar")
inputString <- .jnew("java.lang.String","1000")
inputString %instanceof% "java.lang.String"
StringToNum <- .jnew("com.mingdong.rcalljava.test.StringToNum")
StringToNum %instanceof% "com.mingdong.rcalljava.test.StringToNum"
.jcall(StringToNum,returnSig= "V", "main",inputString )
Error in .jcall(StringToNum, returnSig = "V", "main") :
method main with signature ()V not found
There are two issues. On the Java side in main you call the constructor new StringToNum() which does not exist. The main method should rather look like:
public static void main( String[] args ) {
StringToNum stringToNum = new StringToNum( args[0] );
int num = stringToNum.convertStringToInt();
System.out.println("num:" + num);
}
Maybe this solves already your problem. However, in general you call static methods in Java not on the object but on the class. If you'd call the main method from Java you'd have to call
StringToNum.main( "1000" );
instead of calling
StringToNum obj = new StringToNum( "" );
obj.main( "1000" );
You should also avoid to call the low-level functions (indicated by starting with a .) of the rJava package. So as indicated in rJava .jcall return type issue the proper call would be
J("com.mingdong.rcalljava.test.StringToNum")$main( "1000" ) # untested
Related
Why I can call non-static method length() from class String, but I can't call non-static method lengthHelper( String line ) from my class ExpressionHelper?
public static void main(String[] args) {
String[] lines1 = {"H", "HH", "HHH"};
System.out.println(sum(lines1, String::length));
System.out.println(sum(lines1, s -> s.length()));
System.out.println(sum(lines1, ExpressionHelper::lengthHelper)); //wrong
}
interface Expression {
int length(String line);
}
static class ExpressionHelper {
int lengthHelper(String line) {
return line.length();
}
}
private static int sum(String[] lines, Expression func) {
int result = 0;
for (String i : lines) {
result += func.length(i);
}
return result;
}
String::length is an instance method of String. It requires an instance of String to run, which you are providing, because you are passing elements of lines1 to it.
ExpressionHelper::lengthHelper is an instance method of ExpressionHelper. In addition to the explicit String line argument, it requires an instance of ExpressionHelper to run, which you are not providing.
If you made lengthHelper a static method in ExpressionHelper, then you would be able to call it without an instance of ExpressionHelper.
In addition to the answer from khelwood:
If you change your code like this:
public static void main( String[] args )
{
final var expressionHelper = new ExpressionHelper();
String[] lines1 = {"H", "HH", "HHH"};
System.out.println(sum( lines1, String::length ) );
System.out.println(sum( lines1, s -> s.length() ) );
System.out.println(sum( lines1, ExpressionHelper::lengthHelper) ); //wrong
System.out.println(sum( lines1, expressionHelper::lengthHelper) );
}
it works also with ExpressionHelper::lengthHelper (although I should write better ExpressionHelper.lengthHelper() or ExpressionHelper#lengthHelper to avoid further confusion …)
Yes, I know, in this context it is nasty to name the variable same as the class, only having the first letter as lower case: it does not support readability.
But now expressionHelper is that instance of ExpressionHelper that #khelwood mentioned as missing in their answer.
public class MethodExemple {
public static void main(String[] args) {
MethodExemple methodExemple = new MethodExemple();
methodExemple.StrCombine( x: "hello", y:"hongdroid");
System.out.println(methodExemple.StrHongdroid( hong:"hollo"));
}
public void StrCombine (String x, String y) {
String result = x + y;
System.out.println(result);
}
public String StrHongdroid (String hong, String droid){
String result = hong +droid;
return result;
}
}
I coded as I learned in class. However, an error occurred only in my code. The contents of the error are as follows.
cannot resolve symbol 'x' and 'y'
When calling a method in Java, you shouldn't specify the argument names, just provide them in order:
methodExemple.StrCombine("hello", "hongdroid");
You don't need to include x and y when calling the method StrCombine(). Here is the correct way methodExemple.StrCombine( "hello", "hongdroid"); either passing string literals like this or string variables
I wrote this program to exchange first and last characters in a string.
I created two classes (abc and BackFront). There are no errors in Eclipse but I do not get any output. When I click run I get output of some other class. What am I doing wrong?
Class abc with main:
package puneeth;
import java.lang.*;
public class abc {
public void main(String[] args) {
BackFront object1 = new BackFront();
String str = "chocolate";
object1.frontBack(str);
}
}
Class BackFront:
package puneeth;
import java.lang.*;
public class BackFront {
public String frontBack(String str) {
String mid = str.substring(1,str.length());
String first = str.substring(0,3);
String last = str.substring(str.length());
return last + mid + first;
}
}
That's strange ,make sure you are running the correct file .
The string is changed, but you never physically print it for there to be output. You could do System.out.println(object1.frontBack(str); to get output from the output console.
The error in your code will make you laugh.
First of all, you need to print the returned string. Do this:
String res=object1.frontBack(str);
System.out.println(res);
Secondly, you need to make your main as STATIC. Do this:
public static void main(String [] args)
{
//your code
}
This will solve your problem. Hope this helps :)
Class BackFront:
package puneeth;
public class BackFront {
public void frontBack(String str) {
String result;
StringBuilder sb = new StringBuilder(str);
char first = sb.charAt(0);
sb.setCharAt(0, sb.charAt(sb.length() - 1));
sb.setCharAt(sb.length() - 1, first);
result = sb.toString();
System.out.println(result);
}
}
Class abc with main method:
package puneeth;
public class abc {
public static void main(String[] args) {
BackFront object1 = new BackFront();
String str = "chocolate";
object1.frontBack(str);
}
}
// Result:
// ehocolatc
What type of output are you expecting.
If you are expecting something in the output window you need this:
System.out.println( "My String" );
Identifier error either has ** or is in bold. I also do not know if the rest of the program will work.
import javax.swing.JOptionPane;
public class Multi
{
public static void main (String args[]);
**public static String dataIn (Stringinfo)**
{
String words = "Your hypotenuse is?";
String word1 = "Your second side is?";
String word2 = "Your thrid side is?";
int a = Integer.parseInt (words);
int b = Integer.parseInt (word1);
int c = Integer.parseInt (word2);
if ((a*a+b*b)== (c*c))
{
System.out.println ("Right triangle") ;
}
}
public static String dataIn (String info)
{
String answer = JOptionPane.showInputDialog(info); return answer;
}
}
You are declaring a method main like you would in an interface without a body. However, you can't do this outside an interface so main must have a body
public static void main (String args[]) { }
or be removed.
In addition to what #clcto said about your main method not having a body, there is another problem. You need to specify a data type while adding parameters just like when you create variables.
public static String dataIn (String Stringinfo)
Here String is the data type, just like in your other variables. Change String to be whatever fits your needs best.
public class Star{
public static ArrayList initdata(String pattern) {
ArrayList data = new ArrayList();
if (pattern != "") {
ModelCollection mc = Star.find(pattern, 0);
Iterator dataIterator = mc.iterator();
while (dataIterator.hasNext()) {
Star star = (Star) dataIterator.next();
data.add(star.getName());
Debug.trace("StarName" + star.getName());
}
}
Collections.sort(data);
return data;
}
}
I want to invoke method initdata using reflection, I tried to write something like this , but it does not work:
Class c = Class.forName("com.cubiware.fyretv.application.model.Star");
par[0] = String.class;
Method mthd = c.getMethod("initdata", par);
ArrayList output = (ArrayList) mthd.invoke(null, null);
try
ArrayList output = (ArrayList) mthd.invoke(null, (String)null);
It's not good idea to pass null, when method expects Object...
May be this will help
Calling Java varargs method with single null argument?
First, Your check seems weird to me: try if (pattern != null) instead of if (pattern != "").
Why don't you pass the par array, you have illegal argument exception I think. try passing arguments array.
Object[] args = {"someString / maybe null"};
ArrayList output = (ArrayList) mthd.invoke(null, args);
Obviously, your invoke call is similiar to
initdata(null);
Now, inside initdata you do not filter the case where pattern == null which leads us to a call
Star.find(null, 0);
We do not know the implementation of this method - if we're lucky, we get an empty collection. Otherwise, I expect a NullPointerException either in Star.find or later at mc.iterator()
$ javac -cp dp4j-1.2-SNAPSHOT-jar-with-dependencies.jar -Averbose -All Star.java
Star.java:12:
import com.dp4j.*;
public class Star {
public Star() {
super();
}
public static ArrayList initdata(String pattern) {
return null;
}
#Reflect()
public static void main(String[] args) throws java.lang.ClassNotFoundException, java.lang.IllegalAccessException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException, java.lang.IllegalArgumentException {
final java.lang.reflect.Method initdataWithStringMethod = Class.forName("Star").getDeclaredMethod("initdata", .java.lang.String.class);
initdataWithStringMethod.setAccessible(true);
initdataWithStringMethod.invoke("", new .java.lang.Object[1][]{null});
final java.lang.reflect.Method printlnWithStringMethod = Class.forName("java.io.PrintStream").getDeclaredMethod("println", .java.lang.String.class);
printlnWithStringMethod.setAccessible(true);
printlnWithStringMethod.invoke(System.out, new .java.lang.Object[1][]{"Varargs + reflection? No problem"});
}
}
public static void main(String args[]) {
^
$ java Star
Varargs + reflection? No problem