actually, i'm new in python. Here, i want to get an output from class of python. but here, i input String from java.
here's the java code:
String word;
Scanner in = new Scanner(System.in);
System.out.println("input: ");
word = in.nextLine();
TryinPythonToJavaAgain ie = new TryinPythonToJavaAgain();
ie.execfile("~\\hello.py");
PyInstance hello = ie.createClass("Hello", word);
hello.invoke("run");
python code:
class Hello:
def __init__(self, abc):
self.abc = abc
def run(self):
print(self.abc)
if i input : "hello"
i have an error like this:
input:
hello
Exception in thread "main" Traceback (most recent call last):
File "", line 1, in
NameError: name 'hello' is not defined
Java Result: 1
and if i input >2 word (e.g "hello world"), i have an error like this:
input:
hello world
Exception in thread "main" SyntaxError: ("no viable alternative at input 'world'", ('', 1, 12, 'Hello(hello world)\n'))
Java Result: 1
what should i fix in this code? thanks
If the code in your createClass method looks anything like this ...
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
... then I think you need to add quotes round the opts variable. The code above is from here which works since "None" gets turned into this.interpreter.eval(className(None)) which is valid whereas yours becomes this.interpreter.eval(className(hello world)) which isn't.
I've not tried it, but this.interpreter.eval(className("hello world")) would seem more likely to work.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm very new to the coding space and was wondering if someone could help me start a .jar file. BTW This is using C#. My issue is this wont run the file. I got it to work with .txt files though, so I'm just a bit confused.
private void button1_Click(object sender, EventArgs e)
{
Process.Start("java" , "server.jar");
}
In short, for the answer, add -jar right before the JAR file name.
The accepted answer is not 100% correct for several reasons: it does not recognize whitespace-delimited and whitespace-containing arguments, and may mess up with quote characters that must be passed (therefore properly escaped) to the delegated Java app. In short, do not use Arguments if the string is not known to be a constant (having spaces will require manual escaping anyway), but merely prefer ArgumentList that handles each argument properly.
Here is an example Java application to deal with command line arguments:
public final class SayHello {
private SayHello() {}
public static void main(final String... names) {
for ( final String name : names ) {
System.out.printf("hello %s!\n", name);
}
}
}
The manifest for the JAR file:
Manifest-Version: 1.0
Main-Class: SayHello
Making a JAR file out of it is simple:
javac SayHello.java
jar cfm SayHello.jar MANIFEST.MF SayHello.class
Example of use:
java -jar SayHello.jar 'John Doe' Anonymous
that gives:
hello John Doe!
hello Anonymous!
Now, an example C# program that passes the -jar argument to the java process so that it recognizes the given file as a JAR file and demonstrates what can go wrong with Arguments if passed as a string.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
using System.Diagnostics;
public static class SayHello {
public static void Main() {
// interprets 3 names: John, Doe, Anonymous (wrong)
RunJavaJarBadly1("SayHello.jar", "John Doe Anonymous");
// interprets 1 name: John Doe Anonymous (wrong)
RunJavaJarBadly2("SayHello.jar", "John Doe Anonymous");
// interprets 2 names: John Doe, Anonymous (correct, but bad: requires the first name to be quoted at the call-site)
RunJavaJarBadly1("SayHello.jar", "\"John Doe\" Anonymous");
// interprets 1 name: "John Doe" Anonymous (wrong: interprets everything as a single name)
RunJavaJarBadly2("SayHello.jar", "\"John Doe\" Anonymous");
// interprets 2 names, no ambiguous call, each name is recognized properly, does not require quoting at the call site
RunJavaJar("SayHello.jar", "John Doe", "Anonymous");
}
private static void RunJavaJarBadly1(string jarPath, string argumentsFortheJarFile) {
var process = new Process();
process.StartInfo.FileName = "java";
process.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
process.Start();
process.WaitForExit();
}
private static void RunJavaJarBadly2(string jarPath, string jarArgs) {
var process = new Process();
process.StartInfo = new ProcessStartInfo("java") {
ArgumentList = { "-jar", jarPath, jarArgs }
};
process.Start();
process.WaitForExit();
}
private static void RunJavaJar(string jarPath, params string[] jarArgs) {
var process = new Process();
process.StartInfo = new ProcessStartInfo("java") {
ArgumentList = { "-jar", jarPath }
};
foreach ( var jarArg in jarArgs ) {
process.StartInfo.ArgumentList.Add(jarArg);
}
process.Start();
process.WaitForExit();
}
}
The code above produces (no legend in the output, but added for explanation):
hello John! \_ #1/1: incorrect, the space is ignored
hello Doe! /
hello Anonymous! -- #1/2: correct, no spaces in-between
hello John Doe Anonymous! -- #2/1|2: incorrect
hello John Doe! -- #3/1: correct, but requires the call site to escape the argument
hello Anonymous! -- #3/2: correct, no need to escape, thanks to no spaces
hello "John Doe" Anonymous! -- #4/1|2: incorrect, similar to #2/1|2
hello John Doe! -- #5/1: correct, let the framework do its job
hello Anonymous! -- #5/2: correct, let the framework do its job
In order to get it to work, the file name needs to be "java" and contain the file location in the arguments.
System.Diagnostics.Process clientProcess = new Process();
clientProcess.StartInfo.FileName = "java";
clientProcess.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;
Taken from similar question here
Optional way using ArgumentList:
System.Diagnostics.Process clientProcess = new Process();
var info = new System.Diagnostics.ProcessStartInfo("java.exe")
{
ArgumentList = {
"-jar",
jarPath,
jarArgs
}
};
info.FileName = "java";
clientProcess.StartInfo = info;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;
Here are some options for you to check out.
Also similar question with a working result: here
Paraphrasing from links:
In order to get it to work, the file name needs to be "java" and contain the file location in the arguments.
System.Diagnostics.Process clientProcess = new Process();
clientProcess.StartInfo.FileName = "java";
clientProcess.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;
I am new to Java and Computer science in general, I keep getting the same error from this code:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Trivedi_Chatbot.main(Trivedi_Chatbot.java:28)
Please help me if you can.
import java.util.Scanner;
import java.util.Date;
public class Trivedi_Chatbot
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hi there! My name is Alexa Jr!");
String input = scan.nextLine();
while(!input.equalsIgnoreCase("Goodbye"))
{
if ((input.equalsIgnoreCase("What's up?")) || (input.equalsIgnoreCase("Whats up")))
{
System.out.println ("Roof or sky, depending on if you're in a building.");
}
else if (input.equalsIgnoreCase("What's the date?")){
Date d = new Date();
System.out.println("Today's date is " + d);
}
input = scan.nextLine();
}
System.out.println("Goodbye! See you soon!");
}
}
you need to run your application in cmd or in ide like eclipse or netbeans
exemple on cmd :
https://www.maketecheasier.com/run-java-program-from-command-prompt/
Here's a transcript of your program being run in a terminal:
$ ls
Trivedi_Chatbot.class
$ java Trivedi_Chatbot
Hi there! My name is Alexa Jr!
whats up
Roof or sky, depending on if you're in a building.
goodbye
Goodbye! See you soon!
$ java Trivedi_Chatbot </dev/null
Hi there! My name is Alexa Jr!
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Trivedi_Chatbot.main(Trivedi_Chatbot.java:13)
The exception you get is caused when your program is not reading from a terminal.
I am using Java2Python package to translate a Java project to Python, and I've got an error.
[root#localhost Desktop]# j2py ConfigurationManager.java ConfigurationManager.py
File "/usr/bin/j2py", line 113
except (IOError, ), exc:
^
SyntaxError: invalid syntax
File /usr/bin/j2py, line 113
try:
if filein != '-':
source = open(filein).read()
else:
source = sys.stdin.read()
except (IOError, ), exc:
code, msg = exc.args[0:2]
print 'IOError: %s.' % (msg, )
return code
If there is any information needed, please tell me.
update
File "/usr/bin/j2py", line 115
print 'IOError: %s.' % (msg, )
^
SyntaxError: invalid syntax
Try this :
except (IOError) as exc:
for arg in exc.args:
print(str(arg))
code = exc.args[0]
return code
Here I assume that you want to return 1st value in exc.args
Currently i'm trying to make a basic program that takes an input of any string such as a sentence or a paragraph and it takes each letter and turns it into a 3 character code once i get this working i'm assuming i should just be able to do the reverse and have it take the 3 digit code and turn it back to text, anyway i'm getting an error when i try to compile the program to test it. i have the issue marked below. also once i get the program working i would like to make a gui for it where you put in the input and it shows the out put after you click a button but as i am just starting out that seems a but advanced for me if you know any good tutorials for it please let me know!
import java.util.Scanner;
import java.util.*;
class test {
private static Scanner inp;
public static void main(String[] args) {
Map <Character, String> encryptionMappings = new HashMap<>();
encryptionMappings.put('a',"{qaz}");
encryptionMappings.put('b',"{wsx}");
encryptionMappings.put('c',"{edc}");
encryptionMappings.put('d',"{rfv}");
encryptionMappings.put('e',"{tgb}");
encryptionMappings.put('f',"{yhn}");
encryptionMappings.put('g',"{ujm}");
encryptionMappings.put('h',"{ik,}");
encryptionMappings.put('i',"{ol>}");
encryptionMappings.put('j',"{p;?}");
encryptionMappings.put('k',"{[']}");
encryptionMappings.put('l',"{qwe}");
encryptionMappings.put('m',"{asd}");
encryptionMappings.put('n',"{zxc}");
encryptionMappings.put('o',"{rty}");
encryptionMappings.put('p',"{fgh}");
encryptionMappings.put('q',"{vbn}");
encryptionMappings.put('r',"{yui}");
encryptionMappings.put('s',"{hjk}");
encryptionMappings.put('t',"{nm,}");
encryptionMappings.put('u',"{iop}");
encryptionMappings.put('v',"{qaw}");
encryptionMappings.put('w',"{sxz}");
encryptionMappings.put('x',"{red}");
encryptionMappings.put('y',"{cvf}");
encryptionMappings.put('z',"{ytg}");
encryptionMappings.put('A',"{hnb}");
encryptionMappings.put('B',"{iuj}");
encryptionMappings.put('C',"{kml}");
encryptionMappings.put('D',"{opl}");
encryptionMappings.put('E',"{wom}");
encryptionMappings.put('F',"{wsv}");
encryptionMappings.put('G',"{ths}");
encryptionMappings.put('H',"{imv}");
encryptionMappings.put('I',"{ybf}");
encryptionMappings.put('J',"{cja}");
encryptionMappings.put('K',"{thw}");
encryptionMappings.put('L',"{maz}");
encryptionMappings.put('M',"{pqa}");
encryptionMappings.put('N',"{zwl}");
encryptionMappings.put('O',"{;ld}");
encryptionMappings.put('P',"{'d;}");
encryptionMappings.put('Q',"{;ny}");
encryptionMappings.put('R',"{;ws}");
encryptionMappings.put('S',"{c/.}");
encryptionMappings.put('T',"{%#^}");
encryptionMappings.put('U',"{/mc}");
encryptionMappings.put('V',"{uka}");
encryptionMappings.put('W',"{zby}");
encryptionMappings.put('X',"{&hd}");
encryptionMappings.put('Y',"{&hw}");
encryptionMappings.put('Z',"{^#^}");
encryptionMappings.put('0',"{$g%}");
encryptionMappings.put('1',"{^#%}");
encryptionMappings.put('2',"{142}");
encryptionMappings.put('3',"{243}");
encryptionMappings.put('4',"{089}");
encryptionMappings.put('5',"{756}");
encryptionMappings.put('6',"{423}");
encryptionMappings.put('7',"{312}");
encryptionMappings.put('8',"{145}");
encryptionMappings.put('9',"{187}");
encryptionMappings.put('~',"{)*(}");
encryptionMappings.put('`',"{$#%}");
encryptionMappings.put('!',"{!^#}");
encryptionMappings.put('#',"{#^&}");
encryptionMappings.put('#',"{^#&}");
encryptionMappings.put('$',"{!?*}");
encryptionMappings.put('%',"{^<+}");
encryptionMappings.put('^',"{+$$}");
encryptionMappings.put('&',"{!!*}");
encryptionMappings.put('*',"{((%}");
encryptionMappings.put('(',"{*&^}");
encryptionMappings.put(')',"{$%^}");
encryptionMappings.put('_',"{&#^}");
encryptionMappings.put('-',"{<>?}");
encryptionMappings.put('=',"{:'^}");
encryptionMappings.put('{',"{%%G}");
encryptionMappings.put('}',"{$$$}");
encryptionMappings.put('[',"{***}");
encryptionMappings.put(']',"{:::}");
encryptionMappings.put(':',"{#$%}");
encryptionMappings.put('|',"{?H*}");
encryptionMappings.put(';',"{B&&}");
encryptionMappings.put('"',"{#gs}");
encryptionMappings.put('?',"{^gl}");
encryptionMappings.put('/',"{#gn}");
encryptionMappings.put('<',"{%TG}");
encryptionMappings.put('>',"{5%5}");
encryptionMappings.put(',',"{yty}");
encryptionMappings.put('.',"{ggg}");
inp = new Scanner(System.in);
System.out.println("Input Password");
int n = inp.nextInt();
if(n!=234) {
System.out.println("Denied Acess");
} else {
System.out.print("Password Accepted"
+ " ");
System.out.print("Input Text to encrypt: ");
String m = inp.next();
String encryptMe = "He";
StringBuilder builder = new StringBuilder();
The below line is the one that shows a syntax error for "toCharArray" i'm not sure why, I just started learning java so if its something simple that i'm missing i'm sorry, any and all help is apreciated.
for (Character c : encryptMe.toCharArray) {
builder.append(encryptionMappings.get(c));
}
String encrypted = builder.toString();
}
}
You are trying to call a method on the object but you are missing the empty () that need to follow toCharArray. Some languages allow you to omit the empty parentheses, but Java is not one of them. You should use:
for (Character c : encryptMe.toCharArray()) {
builder.append(encryptionMappings.get(c));
}
A good IDE (Eclipse, Intellij IDEA, Netbeans, etc.) will help you catch these syntax errors as you learn.
I am getting following exception when trying to run my command line application:
java.lang.ExceptionInInitializerError
at org.hibernate.validator.engine.ConfigurationImpl.<clinit>(ConfigurationImpl.java:52)
at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:43)
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.substring(String.java:1937)
at org.hibernate.validator.util.Version.<clinit>(Version.java:39)
... 34 more
Am I doing anything wrong? Please suggest.
This is strange. I pasted the relevant parts of the static initialization block of o.h.v.u.Version in a class with a main and added some poor man's logging traces:
public class VersionTest {
public static void main(String[] args) {
Class clazz = org.hibernate.validator.util.Version.class;
String classFileName = clazz.getSimpleName() + ".class";
System.out.println(String.format("%-16s: %s", "classFileName", classFileName));
String classFilePath = clazz.getCanonicalName().replace('.', '/') + ".class";
System.out.println(String.format("%-16s: %s", "classFilePath", classFilePath));
String pathToThisClass = clazz.getResource(classFileName).toString();
System.out.println(String.format("%-16s: %s", "pathToThisClass", pathToThisClass));
// This is line 39 of `org.hibernate.validator.util.Version`
String pathToManifest = pathToThisClass.substring(0, pathToThisClass.indexOf(classFilePath) - 1)
+ "/META-INF/MANIFEST.MF";
System.out.println(String.format("%-16s: %s", "pathToManifest", pathToManifest));
}
}
And here the output I get when running it:
classFileName : Version.class
classFilePath : org/hibernate/validator/util/Version.class
pathToThisClass : jar:file:/home/pascal/.m2/repository/org/hibernate/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA.jar!/org/hibernate/validator/util/Version.class
pathToManifest : jar:file:/home/pascal/.m2/repository/org/hibernate/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA.jar!/META-INF/MANIFEST.MF
In your case, the StringIndexOutOfBoundsException: String index out of range: -2 suggests that:
pathToThisClass.indexOf( classFilePath )
is returning -1, making the pathToThisClass.substring(0, -2) call indeed erroneous.
And this means that org/hibernate/validator/util/Version.class is somehow not part of the pathToThisClass that you get. I don't have a full explanation but this must be related to the fact that you're using One-Jar.
Could you run the above test class and update your question with the output?
So, as you use One-JAR, the problem probably is in incompatibility between One-JAR and Hibernate Validator. However, in the latest version of One-JAR (0.97) it works fine, therefore use the latest version.