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.
Related
I would like to write a java rule Will generate a issue if an imported class is an APIClass annotation and the imported class has issues. I am following this tutorial.
The code:
First, I wrote a simple rule:
#Rule( key = "ForbidClassVariables", name = "ForbidClassVariables")
public class ForbidClassVariables extends BaseTreeVisitor implements JavaFileScanner {
private JavaFileScannerContext context;
#Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
if (context.getSemanticModel() != null) {
scan(context.getTree());
}
}
#Override
public void visitClass(ClassTree tree) {
if (tree.modifiers().annotations().size() > 0 && hasAnnotation(tree.modifiers().annotations(), "APIClass")) {
if (hasClassVariables(tree)) {
this.context.reportIssue(this, tree.simpleName(), "Do not use class variables on API Classes.");
}
}
super.visitClass(tree);
}
private boolean hasAnnotation(List<AnnotationTree> annotations, String annotationName) {
for (AnnotationTree annotation : annotations) {
if (annotation.annotationType().is(Tree.Kind.IDENTIFIER)
&& ((IdentifierTree) annotation.annotationType()).name().equals(annotationName)) {
return true;
}
}
return false;
}
private boolean hasClassVariables(ClassTree tree) {
for (Tree member : tree.members()) {
if (member.is(Tree.Kind.VARIABLE)) {
VariableTree variableTree = (VariableTree) member;
Symbol symbol = variableTree.symbol();
if (!symbol.isStatic() || !symbol.isFinal()) {
return true;
}
}
}
return false;
}
}
I created a test class file ExampleA.java
package br.com.test;
#APIClass
public class ExampleA {
private String name;
}
When I run the test, generates an error on line 4, It was as expected.
The point of the problem: I created another rule:
#Rule( key = "CheckIFClassIsOK", name = "CheckIFClassIsOK")
public class CheckIFImportedClassIsOK extends BaseTreeVisitor implements JavaFileScanner{
private JavaFileScannerContext context;
#Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
if (context.getSemanticModel() != null) {
scan(context.getTree());
}
}
#Override
public void visitImport(ImportTree tree) {
IdentifierTree identifier = ((MemberSelectExpressionTree) tree.qualifiedIdentifier()).identifier();
System.out.println(identifier); // Shows ExampleA
// At this point I need re-scan ExampleA class and IF the scan generate any issue
// Will generate another here Issue on ExampleB
super.visitImport(tree);
}
}
And used this file to test:
import br.com.test.ExampleA;
public class ExampleB {
private ExampleA exampleA;
}
The problem is, when I am visiting an import, if the imported class has an APIClass annotation and has issues, it will generate an issue on ExampleB.java to avoid using this import because has an issue. I have searched a lot on the Tree classes, but I didn't find anything useful. I think I need to force the re-scan on ExampleA.java, but how? Anyone have ideas?
Sonar version: 6.2
Java plugin version: 4.5.0.8398
Thanks for attention
Unfortunately, this is not possible. There is no way in the API to request parsed tree from another file. However you are able to retrieve semantic information about members in class ExampleB, but this doesn't include annotations.
I need to create a custom function in Jmeter, and because of performance issues I can't use beanshell.
I wrote a java class following http://gabenell.blogspot.com/2010/01/custom-functions-for-jmeter.html and http://code4reference.com/2013/06/jmeter-custom-function-implementation/, but when I compile it I can't seem to get Jmeter to recognize it.
My class:
package custom.functions;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class Username extends AbstractFunction{
private static final List<String> desc = new LinkedList<String>();
private static final String KEY = "__Username";
private int number = 0;
static {
desc.add("Pass a random value to get a valid username for the system.");
}
public Username() {
super();
}
#Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
throws InvalidVariableException {
try {
return getValue(number);
} catch(Exception e){
throw new InvalidVariableException(e);
}
}
public String getValue(int number){
return "John-Smith";
}
#Override
public synchronized void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
checkParameterCount(parameters, 1, 1);
Object[] values = parameters.toArray();
number = Integer.parseInt(((CompoundVariable) values[0]).execute().trim());
}
#Override
public String getReferenceKey() {
return KEY;
}
#Override
public List<String> getArgumentDesc() {
return desc;
}
}
When I run jar tf custom-functions.jar (to verify that the class file is in the jar):
META-INF/
META-INF/MANIFEST.MF
custom/
custom/functions/
custom/functions/Username.class
I placed the jar in my jmeter lib/ext directory and tried running jmeter by itself and with -Jsearch_paths=../lib/ext/custom-functions.jar, but either way when I open the function helper tool it's not listed, and a simple test plan to verify the function sends instead %24%7B__Username%281%29%7D.
Am I not putting the file in the right place? Is it named incorrectly?
You can put groovy-all.jar on the classpath of Jmeter, and then you will be able to run external .groovy scripts or you can add a JSR223-Groovy Sampler.
My problem was that I had compiled my class using Java 8 instead of Java 7, which was the runtime I was using for jmeter.
Hi I saw some of the related question related to this but didn't find any to the point solution.
I have a POJO class defined as:
MpsPojo.java
public class MpsPojo {
private String mfr;
private String prod;
private String sche;
public String getMfr() {
return mfr;
}
public void setMfr(String mfr) {
this.mfr = mfr;
}
public String getProd() {
return prod;
}
public void setProd() {
this.prod = prod;
}
public String getSchema() {
return sche;
}
public void setSchema() {
this.sche = sche;
}
}
I have 2nd business Logic as:: MpsLogic.java
public class MpsLogic {
public void calculateAssert(MpsPojo mpspojo){
String manufacturer;
String product;
String schema;
manufacturer = mpspojo.getMfr();
product = mpspojo.getProd();
schema = mpspojo.getSchema();
String url = "http://localhost:9120/dashboards/all/list/"+manufacturer+"/"+product+"/"+schema;
}
}
And final class, the Test class is :: FinalLogic.java
public class FinalLogic {
MpsPojo mpspojon = new MpsPojo();
MpsLogic mpslogicn = new MpsLogic();
#Test
public void firstTest() {
mpspojon.setMfr("m1");
mpspojon.setProd("p1");
mpspojon.setSchema("sch1");
mpslogicn.calculateAssert(mpspojon);
System.out.println("Printing from Final class");
}
}
In program FinalLogic.java, this gives me the Compilation error error method setSchema in class MpsPojo cannot be applied to given types;
But when I comment the lines mpspojon.setProd("p1"); and mpspojon.setSchema("sch1"); then this works fine without error.
I debugged a lot but dint find any clue for this. Any help will be very helpful for me.
Thanks
Add String arguments to setProd and setSchema as you have already done with setMfr:
public void setProd(String prod) {
^ ^
and
public void setSchema(String sche) {
^ ^
setSchema() receives no parameters in your declaration. Change it to:
public void setSchema(String sche) {
this.sche = sche;
}
Same holds true for setProd
If you use any IDE, I advise you:
look into the warnings that you will get (the assignment this.sche = sche will give warning The assignment to variable thing has no effect in case of no argument method).
Generate the setters/getters automatically, don't code them by yourself (thus avoiding any possible typing mistakes). E.g. in Eclipse that will be alt+shift+s, then r
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.
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.