I was wondering if someone could help me with this.
I have defined my interface as:
interface Model
{
public String toString();
public Model add (Model m);
}
There are 2 classes implementing the interface (ClassA and ClassB):
class ClassA implements Model
{
private int val;
public ClassA(int x)
{
val = x;
}
public String toString()
{
return ""+ "value of object of class A is " + val;
}
public Model add (Model m)
{
if (m instanceof ClassA)
return new ClassA(val + ( (ClassA) m).val);
else
return null;
}
}
class ClassB implements Model
{
private String str;
public ClassB(String s)
{
str = s;
}
public String toString()
{
return str;
}
public Model add (Model m)
{
if (m instanceof ClassB)
return new ClassB(str + ((ClassB) m).str);
else
return null;
}
}
My main defines objects of ClassA and ClassB and calls their tostring() methods.
public class Example {
public static void main (String args[]) {
ClassA a = new ClassA(5);
ClassB b= new ClassB("Hi");
Model m = b;
System.out.println(m.toString());
ClassA a1 = new ClassA(7);
m = a.add(a1);
System.out.println(m);
}
}
When I try to build this file it compiles fine but, upon trying to run the application I get an error message:
"Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file).....etc...etc"
Can anyone help me with this? It's probably something simple. I'm a beginner Java student.
There is no error in your program.Your program is absolutely ok. But , I do not know which command you are writing for execution .Try once again with absolute path setting to JDK and JRE.
Command like:-
for Compile -javac Example.java
for Run -java Example
It will successfully run. Hope it will help you.
Related
I'm making a game with libGDX that I want to export to HTML using Gradle. The issue comes when I use this method to get a list of actors. Apparently isInstance() and isInstanceOf are not compatible with GWT so I'm looking for a way to get around this. Gradle tell me isInstance is not defined. It runs fine on desktop.
public static ArrayList<BaseActor> getList(Stage stage, String className) {
ArrayList<BaseActor> list = new ArrayList<BaseActor>();
Class theClass = null;
try {
theClass = ClassReflection.forName("com.mygdx.game.actors." + className);
} catch (Exception error) {
error.printStackTrace();
}
for (Actor a : stage.getActors()) {
if (theClass.isInstance(a))
list.add((BaseActor) a);
}
return list;
}
The Actor class has a user object property (getUserObject()/setUserObject()) that you can use to attach data. You could make your BaseActor use this as a class tag property, and use an abstract method so you won't forget to add it to any of your Actor implementations.
abstract class BaseActor {
//...
public BaseActor() {
setUserObject(getClassTag());
//...
}
protected abstract String getClassTag();
}
class SomeSpecificActor extends BaseActor {
public SomeSpecificActor () {
super();
//...
}
#Override
protected String getClassTag() {
return "SomeSpecificActor";
}
}
public static ArrayList<BaseActor> getList(Stage stage, String classTag) {
ArrayList<BaseActor> list = new ArrayList<BaseActor>();
for (Actor a : stage.getActors()) {
if (classTag.equals(a.getUserObject()))
list.add((BaseActor) a);
}
return list;
}
I have a php file which stores a Json string in a $result. I now have a java program which processes it and the main func returns a string array.
Being new to java,Im not sure what argument to pass while creating a run configuration. And when i try to export the runnable jar(leaving the run config arguments empty), it says main method not found in the class. I feel its something to do with the argument passing, but im not sure how to do it. Sorry for this noob question.
Here are my codes:
package jiraBurnDown;
public class JiraCurrentSprintBurnDownDataAttributes {
public long _startTime = 0;
public long _endTime = 0;
public String sprintResponse;
public String _statisticsField = "";
public Map<String, JSONArray> _changes = new HashMap<String, JSONArray>();
public Map<String, IssueState> _changesByIssue = new HashMap<String, IssueState>();
public class IssueState {
public boolean isInSprint = false;
public Double estimatedWork = 0.0;
public IssueState(boolean isInSprint, Double estimatedTime) {
this.isInSprint = isInSprint;
this.estimatedWork = estimatedTime;
}
public String[] main(String sprintResponse) {
String res[]=null;
JSONObject obj = (JSONObject) JSONValue.parse(sprintResponse);
if (obj != null) {
//createEmptySeries();
res=extractAllInfo(obj);
}
else
System.out.println("Not Working ");
return res;
}
}
private String[] extractAllInfo(JSONObject obj) {
String statisticField =extractStatisticsFieldName(obj);
String time=extractStartAndEndTime(obj);
String changes=extractChangesInfo(obj.get("changes"));
String workData=extractAndSaveBaseLine(obj.get("workRateData"));
String scopeChanges=extractAndSaveScopeChange();
String[] info=new String[5];
info[0]=statisticField;
info[1]=time;
info[2]=changes;
info[3]=workData;
info[4]=scopeChanges;
return info;
}
private String extractStatisticsFieldName(JSONObject obj) {
Object rawObj = obj.get("statisticField");
if (rawObj != null && rawObj instanceof JSONObject) {
_statisticsField = ((JSONObject) rawObj).get("name").toString();
//addPoint(DataAttributes.DEFAULT_SERIES_NAME, _statisticsField);
}
return _statisticsField;
}
//and other functions to process the JSON obj
and my php file is
$result=curl_exec($ch);
curl_close($ch);
$result=json_decode($result, true);
$result=json_encode($result);
$out=shell_exec("java -jar /JiraInfo.jar $result");
var_dump($out);
I believe you need a main() method that is called to initialize your java Class. The JSON will then be passed in the args[] variable.
In addition I would quote the JSON string you're sending via CLI.
The main method in java should look like this
public static void main(String[] args){
}
the class that contains this method is called Main Class
and because the main() method should be void, and in order to return result or output to your php, you can use System.out.print(), you will have to figure out an approach to pass array as result, (maybe format the result as JSON too)
for run configuariton you can mention the main class name in the command itself
$out=shell_exec("java -jar /JiraInfo.jar com.my.package.fooClass $result");
or set it in the manifest of JAR file.
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
Main-Class: com.my.package.fooClass
I am implementing a java program in ubuntu without an IDE that converts a currency to €, i have 2 classes ConvertiEuro and Valuta both in the same directory (package) called finanza, the class ConvertiEuro uses the class Valuta, when i try to compile Valuta.java it compiles correctly but when i compile ConvertiEuro.java I get an error saying "ConvertiEuro.java:3: error: cannot find symbol" I don't know why here is the code
package finanza;
public class Valuta {
private String nomeValuta;
private double totValuta;
public Valuta(String nomeVal, double totVal) {
nomeValuta = nomeVal;
totValuta = totVal;
}
public String getNomeValuta() {
return nomeValuta;
}
public double getTotValuta() {
return totValuta;
}
}
package finanza;
import finanza.Valuta;
public class ConvertiEuro {
private int valuteGestibili;
private int cont = 0;
private Valuta [] valutas;
public ConvertiEuro(int valuteGest) {
this.valuteGestibili = valuteGest;
this.valutas = new Valuta [this.valuteGestibili];
}
public boolean impostaValuta(Valuta val){
if(cont<valuteGestibili) {
this.valutas[cont] = val;
cont ++;
return true;
}
else {
return false;
}
}
}
and this how I compile: javac ConvertiEuro.java
I strongly suspect the problem is in how you're compiling.
Both ConvertiEuro.java and Valuta.java should be in a directory called finanza, and you should ideally compile from the parent directory, so that all the compiler knows where to find other code in the same package. It would expect to find a source file in a finanza directory under the one you're currently in, for a package called finanza.
It's simplest just to compile all the files at the same time though:
javac finanza/*.java
... or better yet, use an IDE which will manage this sort of things for you.
Given these classes:
public class VersionVOV1 extends BaseVO {
private String fieldOne = null;
public String getFieldOne() {
return fieldOne;
}
public void setFieldOne(String fieldOne) {
this.fieldOne = fieldOne;
}
public class VersionVOV2 extends BaseVO {
private String fieldFour = null;
public String getFieldFour() {
return fieldFour;
}
public void setFieldFour(String fieldFour) {
this.fieldFour = fieldFour;
}
}
public class BaseVO {
// common code here
}
I have a calling method doSomething which returns a specific child class based upon an input string:
public BaseVO doSomething(String version) {
BaseVO versionVO = doSomethingVersioned(createVersionVO(version));
return versionVO;
}
The remaining methods are:
private BaseVO createVersionVO(String version) {
BaseVO versionVO = null;
if (version.equalsIgnoreCase("V1")) {
versionVO = new VersionVOV1();
} else if (version.equalsIgnoreCase("V2"))
versionVO = new VersionVOV2();
return versionVO;
}
protected VersionVOV1 doSomethingVersioned(VersionVOV1 versionVO) throws Exception {
versionVO.setFieldOne("The versionVO is of type: " + versionVO.getClass());
versionVO.setFieldTwo("Field two");
versionVO.setFieldThree("Field three");
return versionVO;
}
protected VersionVOV2 doSomethingVersioned(VersionVOV2 versionVO) throws Exception {
versionVO.setFieldOne("The versionVO is of type: " + versionVO.getClass());
versionVO.setFieldThree("Field three");
versionVO.setFieldFour("Field four");
return versionVO;
}
As you can see I've overridden doSomethingVersioned to take in a specific child class. My problem however lies with the compilation error that looks like this on doSomethingVersioned: The method doSomethingVersioned(VersionVOV1) in the type VersionExample is not applicable for the arguments (BaseVO).
I've tried returning a type of <T extends BaseVO> from createVersionVO but then I get other compilation errors in that method stating Type mismatch: cannot convert from VersionVOV1 to T.
I feel like this should be easier than I'm making it. How can I keep this overall pattern but allow this to compile?
Thanks to everyone who helps!
What you want is the pattern Factory Method. Note: there really is no benefit from genericity here. You are merely creating something then the presumption is it will go on its way. Generics tend to yield the greatest benefit when you are wanting to leverage code that is orthogonal to the domain objects, e.g. collections.
Still working on the same project (Java-based shell) and tried to run it - and got a strange error. I was working with a single class that represents one of the commands, and, because of the fact that school computers have no compilers, I use ideone. Anyway, I am getting an error and, while I have seen it before, the placement is really weird. The error:
Main.java:56: error: no enclosing instance of type LIST_Command is in scope
public FAKE_CMD(int i) {this.msg = i;System.out.println(i);}
^
Shouldn't this be in a place that is CALLING the constructor, or a static method of the class?
And here is the code (in its entirety, let me know what I should trim or edit it out yourself) Yes, this makes it an SSCCE.
package javashell.ver2.command;
import java.io.*;
import java.util.*;
class LIST_Command { /*extends Command*/
public static Map<String, Command> commands = new HashMap<>();
public String description() {
return "List all commands, their descriptions, or usages.";
}
public String usage() {
return "list <cmds | desc | usage>";
}
public boolean runCmd(String[] cmdArgs, PrintStream output) {
try {
if (cmdArgs.length == 0) {
return false;
}
else if (cmdArgs.length > 0) {
if (cmdArgs[0].equals("cmds")) {
for (Map.Entry<String, Command> cmd : /*main.Main.*/commands.entrySet()) {
output.println(cmd.getKey());
}
}
else if (cmdArgs[0].equals("desc")) {
for (Map.Entry<String, Command> cmd : /*main.Main.*/commands.entrySet()) {
output.println(cmd.getValue().description());
}
}
}
return true;
}
catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
commands.put("test1", new FAKE_CMD(1));
commands.put("test2", new FAKE_CMD(2));
new LIST_Command().runCmd(new String[] {"cmds"}, System.out);
}
abstract class Command {
public abstract String usage();
public abstract String description();
public abstract boolean runCmd(String[] cmdArgs, PrintStream output);
}
static class FAKE_CMD extends Command {
int msg;
public FAKE_CMD(int i) {
this.msg = i;
System.out.println(i);
}
public String usage() {
return "usagetest" + msg;
}
public String description() {
return "descriptiontest" + msg;
}
public boolean runCmd(String[] cmdArgs, PrintStream output) {
return true;
}
}
}
Command is an inner class, which doesn't seem to make sense since it is contained in a class that should be its subclass. Anyway, that is the cause of your error: regardless of whether FAKE_CMD is itself static or not, it needs an enclosing instance of LIST_Command since it extends Command.
Note a possible subtlety in Java's terminology: inner class means a non-static nested class, therefore it implies the need for an enclosing instance.
The constructor of FAKE_CMD need to call its superclass' (Command's) constructor. However, since the superclass is not static, Java has no way of instantiate a superclass instance before constructing a FAKE_CMD.