How to import stddraw correctly? - java

Editor: IntelliJ CE
What I want: Be able to write
setCanvas(500,500);
Instead of
StdDraw.setcanvas(500,500);
Problem: I can't figure out how to correctly import the Stddraw library.
If i simply do
import StdDraw;
IntelliJ tells me "StdDraw" symbol cannot be resolved.
If I comment it out I can call methods from StdDraw but I have to write
StdDraw.setcanvas(500,500);
StdDraw.java is in the same directory as Solver.java.
Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
// import StdDraw;//StdDraw is in the same directory as Solver
public class Solver {
public static void main(String[] args) {
System.out.println("Solver main is running.");
StdDraw.setCanvasSize(500, 500);
StdDraw.setPenColor(StdDraw.RED);
StdDraw.filledRectangle(0,0,10,10);
}
}
I've already tried:
- Making sure Stddraw.java is in the same directory as the file I'm compiling and running
- Looking at http://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html
- Searching for COMPLETE code examples, ie. code that shows how to import the library
- Searching YouTube tutorials
- Reading https://www.jetbrains.com/idea/help/library.html
- Fiddling around with adding stuff in front of StdDraw, eg. stblib.StdDraw

You need to add Stdlib to your local libraries of your java project.
StdDraw is part of this Stdlib library.
First you need to download the stdlib.jar file
Then you create a folder in your java project (name it "lib")
Copy & Paste the stdlib.jar inside the lib folder
Open your java project with IntelliJ.
Click File -> Project Structure -> Modules -> Dependencies
Click on the + sign and choose Library -> Java
Then you need to select your stdlib.jar inside your lib folder
Now you can use the StdDraw class. You don't need to import the class at the top of the file.

I use StdDraw all the time
Under your package declaration, type:
import stddraw.StdDraw;
then all the stuff you need to do should work, also make sure the actual class is inside of your file correctly

Add this import to your class.
import static StdDraw.*;
What it means is that all static methods of the StdDraw class can be used without prefixing them with StdDraw. It also assumes that StdDraw class is in the default package, which is generally frowned upon but appears to be what that library has done.

You said:
What I want: Be able to write
setCanvas(500,500);
Instead of
StdDraw.setcanvas(500,500);
Isn't that against the basic rules of Java?
You cannot write
setCanvas(500,500);
unless you are inside the "StdDraw" class where other methods of the "StdDraw" class call the "setCanvas" method.
Otherwise, either you have to create an instance of the "StdDraw" class first:
e.g. StdDraw stdDraw = new StdDraw();
and then use that instance to call the method:
e.g. stdDraw.setCanvas(500,500);
or you call the method this way:
StdDraw.setcanvas(500,500);
This is the basic knowledge of Java, right?
By the way, if the "StdDraw" class is in the same directory as class "Solver", you don't have to import it to use it.
I use eclipse. I put class "StdDraw" in the same package with other classes. This way, I don't have to use the "import" key word to import "StdDraw". I just use the methods of "StdDraw" the static way. You import it only when it is not in the same package.
FYI: I'm reading Robert Sedgewick's "Algorithms", in which I've never seen any direct calls to methods like the way you want:
uniform(N-i); or
printf("%.2f\n", x); or
point(x0, y0); or
line(x0, y0, x1, y1); or
circle(x, y, r); or
square(x, y, r); or
polygon(x, y); etc. etc....
Instead, it's always:
StdRandom.uniform(N-i); or
StdOut.printf("%.2f\n", x); or
StdDraw.point(x0, y0); or
StdDraw.line(x0, y0, x1, y1); or
StdDraw.circle(x, y, r); or
StdDraw.square(x, y, r); or
StdDraw.polygon(x, y); etc. etc....
I hope this helps.

You can download the library stdlib.jar here: http://introcs.cs.princeton.edu/java/stdlib/
Then import it follow this tutorial:https://stackoverflow.com/a/32853178/2048865

Related

How can I fix the project build path error? I can't import the java.lang.math for a Java 8/9 Calculator app

I am developing a simple calculator application in Java 8/9 in Eclipse. I am working on the power operation (as in "to the power of" used in math). I want to use the Math.power() instead of a for loop. However, I am having trouble importing the java math package into the program. The internet says to add import java.lang.math. When I try to code it in, I receive a notice of "Cannot Perform Operation. This compilation unit is not on the build path of the Java Project". What am I overlooking and/or doing wrong? Please provide suggestions or feedback.
Please note: Yes this is an academic assignment. To make this clear, I am not asking for the coding of the power operation. This issue is specifically about the importing the math package.
power operation (power.java)
package org.eclipse.example.calc.internal.operations;
import org.eclipse.example.calc.BinaryOperation;
// import java.lang.math; produces error
// Binary Power operation
public class Power extends AbstractOperation implements BinaryOperation {
// code removed. not relevant to SOF question.
}
Main (calculator.java)
package org.eclipse.example.calc.internal;
import org.eclipse.example.calc.BinaryOperation;
import org.eclipse.example.calc.Operation;
import org.eclipse.example.calc.Operations;
import org.eclipse.example.calc.UnaryOperation;
import org.eclipse.example.calc.internal.operations.Power;
import org.eclipse.example.calc.internal.operations.Equals;
import org.eclipse.example.calc.internal.operations.Minus;
import org.eclipse.example.calc.internal.operations.Plus;
import org.eclipse.example.calc.internal.operations.Divide;
import org.eclipse.example.calc.internal.operations.Square;
public class Calculator {
private TextProvider textProvider;
private String cmd;
private boolean clearText;
private float value;
public static String NAME = "Simple Calculator";
public Calculator(TextProvider textProvider) {
this.textProvider = textProvider;
setupDefaultOperations();
}
private void setupDefaultOperations() {
new Power();
new Equals();
new Minus();
new Plus();
new Divide();
new Square();
}
....
BTW, I use camel Case normally, but the academic project name everything including file names in standard writing format.
EDIT: After reading a response, I realized I forget to mention this. I can't get any further than typing import java., then the error pop-ups. Then I can't type the rest of the import statement
Image of package hierarchy
Your project is not configured correctly. You have no source dir at all. The src dir should be marked as source dir; right click it and tell eclipse about this, or, as it is a maven project, it's more likely a broken pom. Also, why are you using the org.eclipse package? If you work for SAP, it should be com.sap.

Running java program by considering import dependencies

I have java file at location.
/root/Desktop/software/UIMA/yagogit/yodaqa/src/main/java/cz/brmlab/yodaqa/analysis/question/FocusGenerator.java
This file is part of entire project - FocusGenerator.java
it is importing couple of classes from UIMA and few other packages. (I already configure UIMA on my system)
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.UimaContext;
import org.apache.uima.resource.ResourceInitializationException;
import cz.brmlab.yodaqa.model.TyCor.LAT;
import cz.brmlab.yodaqa.provider.OpenNlpNamedEntities;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
While executing entire projects following readme file, it works well. But I wanted to test each individual program, like one mentioned above. When I try to compile using javac it gives error, cannot find symbol as below
ATByFocus.java:77: cannot find symbol
symbol : class ImplicitQLAT
location: class cz.brmlab.yodaqa.analysis.question.LATByFocus
addFocusLAT(jcas, focus, "amount", null, 33914, 0.0, new ImplicitQLAT(jcas));
^
LATByFocus.java:83: cannot find symbol
symbol : class LAT
location: class cz.brmlab.yodaqa.analysis.question.LATByFocus
addFocusLAT(jcas, focus, text, pos, 0, 0.0, new LAT(jcas));
and so on.
What is correct way to execute this file. I tried it importing in eclipse to, but in eclipse too it could not be imported as project.
It is difficult to build pieces of YodaQA in isolation. I think it's much simpler to just work within YodaQA, but create your custom main class which will directly call the FocusGenerator or any other class you want.
To add another main class and execute it, you will need to add another gradle target. See build.gradle for a few examples already: tsvgs, biocrftrain, etc.

can I load user packages into eclipse to run at start up and how?

I am new to java and to the eclipse IDE.
I am running Eclipse
Eclipse SDK
Version: 3.7.1
Build id: M20110909-1335
On a windows Vista machine.
I am trying to learn from the book Thinking in Java vol4.
The author uses his own packages to reduce typing. However the author did not use Eclipse and this is where the problem commes in..
This is an example of the code in the book.
import java.util.*;
import static net.mindview.util.print.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
print("this does not work");
}
this is the contents of print.Java
//: net/mindview/util/Print.java
// Print methods that can be used without
// qualifiers, using Java SE5 static imports:
package net.mindview.util;
import java.io.*;
public class Print {
// Print with a newline:
public static void print(Object obj) {
System.out.println(obj);
}
// Print a newline by itself:
public static void print() {
System.out.println();
}
// Print with no line break:
public static void printnb(Object obj) {
System.out.print(obj);
}
// The new Java SE5 printf() (from C):
public static PrintStream
printf(String format, Object... args) {
return System.out.printf(format, args);
}
} ///:~
The error I get the most is in the statement.
Import static net.mindview.util.print.*;
On this staement the Eclipse IDE says it cannot resolve net
also on the
print("this does not work");
The Eclipse IDE says that the class print() does not exist for the class HelloWorld.
I have been trying to get these to work, but with only limited success, The autor uses another 32 of these packages through the rest of the book.
I have tried to add the directory to the classpath, but that seems to only work if you are using the JDK compiler. I have tried to add them as libraries and i have tried importing them into a package in a source file in the project. I have tried a few other things but cant remember them all now.
I have been able to make one of the files work, the print.java file I gave the listing for in this message. I did that by creating a new source folder then making a new package in that foldeer then importing the print.java file into the package.
But the next time I try the same thing it does not work for me.
What I need is a way to have eclipse load all these .java files at start up so when I need them for the exercises in the book they will be there and work for me, or just an easy way to make them work everytime.
I know I am not the only one that has had this problem I have seen other questions about it on google searches and they were also asking about the Thinking In Java book.
I have searched this site and others and am just not having any luck.
Any help with this or sugestions are welcome and very appreciated.
thank you
Ok I have tried to get this working as you said, I have started a new project and I removed the static from the import statement, I then created a new source folder, then I created a new package in the source folder. Then I imported the file system and selected the the net.mindview.util folder.
Now the immport statement no longer gives me an error. But the the print statement does, the only way to make the print statement work is to use its fully qualified name. Here is the code.
import net.mindview.util.*;
public class Hello2 {
public static void main(String[] args) {
Hello2 test = new Hello2();
System.out.println();
print("this dooes not work");
net.mindview.util.Print.print("this stinks");
}
}
The Error on the print statement is:
The method print(String) is undefined for the type Hello2
and if I try to run it the error I get is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print(String) is undefined for the type Hello2
at Hello2.main(Hello2.java:6)
The Statement::::: net.mindview.util.Print.print("this stinks") is the fully qualified print statement and it does not throw an error but it does totally defeat the purpose of the print.java file..
If you have any questions please ask Ill get back to you as soon as I can.
I've had similar issues. I solved it by following the steps below:
Click File->New->Java Project. Fill in UtilBuild for the ProjectName. Chose the option "Use project folder as root and click 'Finish'.
Right-click on UtilBuild in the PackageExplorer window and click New->package. For the Package Name, fill in net.mindview.util
Navigate within the unzipped Thinking In Java (TIJ) folder to TIJ->net\mindview\util. Here you will find all the source code (.java) files for util.
Select all the files in the net\mindview\util folder and drag them to the net.mindview.util package under UtilBuild in Eclipse. Chose the 'Copy Files' option and hit 'OK'.
You will probably already have the 'Build Automatically' option checked. If not, go to Project and click 'Build Automatically'. This will create the .class files from the .java source files.
In Eclipse, right-click on the project you were working on (the one where you couldn't get that blasted print() method to work!) Click Properties and Java Build Path->Libraries. Click 'Add Class Folder...' check the box for UtilBuild (the default location for the .class files).
I think the confusion here arises due to CLASSPATH. If you use Eclipse to build and run your code then Eclipse manages your CLASSPATH. (You don't have to manually edit CLASSPATH in the 'Environment Variables' part of your computer properties, and doing so changes nothing as far as Eclipse Build and Run are concerned.)
In order to call code that exists outside your current project (I will name this 'outside code' for convenience) you need to satisfy three things:
A. You need to have the .class files for that code (as .class files or inside a JAR)
B. You need to indicate in your source code where to look for the 'outside code'
C. You need to indicate where to start looking for the 'outside code'
In order to satisfy these requirements, in this example we:
A. Build the project UtilBuild which creates the .class files we need.
B. Add the statement import static net.mindview.util.Print.*; in our code
C. Add the Class Folder library in Eclipse (Java Build Path->Libraries).
You can investigate the effect of Step C by examining the .classpath file that lives directly in your project folder. If you open it in notepad you will see a line similar to the following:
<classpathentry kind="lib" path="/UtilBuild>
You should combine this with your import statement to understand where the compiler will look for the .class file. Combining path="/UtilBuild" and import static net.mindview.util.Print.*; tells us that the compiler will look for the class file in:
UtilBuild/net/mindview/util
and that it will take every class that we built from the Print.java file (Print.*).
NOTE:
There is no problem with the keyword static in the statement
import static net.mindview.util.Print.*;
static here just means that you don't have to give specify the class name from Print.java, just the methods that you want to call. If we omit the keyword static from the import statement, then we would need to qualify that print() method with the class it belongs to:
import net.mindview.util.Print.*;
//...
Print.print("Hello");
which is slightly more verbose than what is achieved with the static import.
OPINION:
I think most people new to Java will use Eclipse at least initially. The Thinking in Java book seems to assume you will do things via command line (hence it's guidance to edit environment variables in order to update CLASSPATH). This combined with using the util folder code from very early in the book I think is a source of confusion to new learners of the language. I would love to see all the source code organised into an Eclipse project and available for download. Short of that, it would be a nice touch to include the .class files in just the 'net/mindview/util' folder so that things would be a little easier.
U should import package static net.mindview.util not static net.mindview.util.Print
and you should extend the class Print to use its method.......
You should remove the static keyword from your import decleration, this: import static net.mindview.util.print.*; becomes this: import net.mindview.util.print.*;
If that also does not work, I am assuming you did the following:
Create your own project;
Start copying code directly from the book.
The problem seems to be that this: package net.mindview.util; must match your folder structure in your src folder. So, if your src folder you create a new package and name it net.mindview.util and in it you place your Print class, you should be able to get it working.
For future reference, you should always make sure that your package decleration, which is at the top of your Java class, matches the package in which it resides.
EDIT:
I have seen your edit, and the problem seems to have a simple solution. You declare a static method named print(). In java, static methods are accessed through the use of ClassName.methodName(). This: print("this dooes not work"); will not work because you do not have a method named print which takes a string argument in your Hello2 class. In java, when you write something of the sort methodName(arg1...), the JVM will look for methods with that signature (method name + parameters) in the class in which you are making the call and any other classes that your calling class might extend.
However, as you correctly noted, this will work net.mindview.util.Print.print("this stinks");. This is because you are accessing the static method in the proper way, meaning ClassName.methodName();.
So in short, to solve your problem, you need to either:
Create a method named print which takes a string argument in your Hello2 class;
Call your print method like so: Print.print("this stinks");
Either of these two solutions should work for you.
In my case I've dowloaded and decompressed the file TIJ4Example-master.zip. in eclipse workspace folder. The three packages : net.mindview.atunit, net.mindview.simple and net.mindview.util are in this point of the project :
and java programs runs with no problems (on the right an example of /TIJ4Example/src/exercises/E07_CoinFlipping.java)

Having trouble getting packages to recognize

I have two different packages inside of my application. The trouble I am having is the packages wont recognize each other.
package sticyface.androidgames.framework.impl;
package sticyface.androidgames.framework;
when I try to import a java file from one to the other I receive an error under stickyface. It says "The import sticyface cannot be resolved.Example
import stickyface.androidgames.framework.Input.TouchEvent;
What am I forgetting to do?
Check your filesystem, you may have created two different structures on the filesystem (which the package definition mirrors.
stickyface.androidgames.framework.Input.TouchEvent -> {src dir}/stickyface/androidgames/framework/Input/TouchEvent.class
So if TouchEvent.class is not in that directory then it can't be imported in. You can also try replacing TouchEvent with * in the import line just in case, that'll import in what needs dynamically.

Import a class in Scripting java (javax.script)

I want to import a class that I made in my project, into my script
I did this but it doesn't work:
function doFunction(){
//Objectif Mensuel
importPackage(java.lang);
importClass(KPDataModel.KPData.KPItem); //ERROR HERE, this is my class that I want to import
KPItem kpItem = kpItemList.get(0);
System.out.println(kpItem.CellList.get(2).Value);
System.out.println("-------");
var proposedMediationSum = Integer.parseInt(kpItemList.get(0).CellList.get(2).Value);
var refusedMediationSum = Integer.parseInt(kpItemList.get(0).CellList.get(3).Value)
var totalMediation = proposedMediationSum + refusedMediationSum;
kpItemList.get(0).CellList.get(4).Value = totalMediation;
}
Well, thnx a lot, I found that the problem comes from the import.
This is what it said in the Oracle website :
The Packages global variable can be
used to access Java packages.
Examples: Packages.java.util.Vector,
Packages.javax.swing.JFrame. Please
note that "java" is a shortcut for
"Packages.java". There are equivalent
shortcuts for javax, org, edu, com,
net prefixes, so pratically all JDK
platform classes can be accessed
without the "Packages" prefix.
So, to import my class I used : importClass(Packages.KPDataModel.KPData.KPItem);

Categories