I am testing a few Java API, I've created my project called 'MyLearning' where all my src files are located, in src I created another Package callede 'myfiles', now when I import the java.nio.file.Files API, IntelliJ doesn't show me suggestions for this class. But in the main package i.e src folder, the suggestion works totally fine.
Example:
The above picture shows my main src folder, where the Files API works totally fine.
But then in the new Package that I've created i.e myfiles, it is showing error on retrieving the methods of Files API. Error is
Cannot resolve symbol 'exists'
Can anyone tell me what could be the poblem here?
You have to put method calls inside a method.
public void foo()
{
Files.exists(path);
}
I also noticed that one of the tags you put is intellij-14. The latest version of IntelliJ is 2016.2.
You have to call it in a method, not in the class
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
Path path = Paths.get("C:\\log.txt");
System.out.println(Files.exists(path));
}
}
Related
Purpose
I want to be able to create a package and call it.
Alternatively, I would like to create separate files for my method (to avoid having x classes in one file).
Setup
Here is my LetterGrader.java file:
package grade.util;
import java.util.*;
import java.io.*;
public class LetterGrader {
private void readArgs() {
System.out.println("Hello, read CLA!");
}
}
Here is my TestLetterGrader.java file:
import java.util.*;
import java.io.*;
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Steps Taken
First, I compile LetterGrader:
This auto creates the bin/grade/util/LetterGrader.class file
javac -d bin -sourcepath src src/grade/util/LetterGrader.java
Here is my working directory at this point
Second, I compile TestLetterGrader:
This fails
javac -d bin -sourcepath src src/grade/util/TestLetterGrader.java
The error message:
src/grade/util/TestLetterGrader.java:6: error: cannot find symbol
LetterGrader letterGrader = new LetterGrader(); // instantiate
^
symbol: class LetterGrader
location: class TestLetterGrader
Question
I believe I am misunderstanding how to call a classes from separate files (in the same location). How can I accomplish this?
You are importing class that is in bin folder. Don’t do that it would not work. You don’t need any import, because the classes are in the same place. Make package under src folder and place the classes there. Remove package grade.util and rename it to the package where you place the classes.
File structure:
src
\
\
yourpackage
\
\
LetterGrader.java TestLetterGrader.java
Then delete everything in your build folder and compile the classes. Java will make it’s magic. You do need to worry about bin folder, it is only for storing compiled classes.
Classes will look like this:
//package name that you created
package yourpackage;
public class LetterGrader {
//need to be public when calling from another class
public void readArgs() {
System.out.println("Hello, read CLA!");
}
}
And
//folder that you placed the .java files
package yourpackage;
//without any import
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Your second question:
You can use classes from other folders, but you you have to import them and they have to be under src folder.
Tell you have class A.java in folder Second and class B.java in folder Main. You will import the the folder in this case import Second.A;
And then call the class A a = new A();
When you have method in a that you want to call simply do:
a.yourmethod();
You have to change private void ... to public void... because you cannot call private outside of the class.
When you are running compiled classes they have to be in the same folder.
Thanks #maratonec for the guidance.
My initial mistake was that I was misunderstanding/misassigning the classpath assignment variable when running a program via terminal. The below helped me.
Compiling and Running a Java Program (on a PC)
• Set the working directory (say, JavaBook)
C:\> cd JavaBook
• Compile HelloWorld.java
C:\JavaBook> javac -d bin src\HelloWorld.java
•Run the program
C:\JavaBook> java -classpath bin HelloWorld
Also, the approach of having all my class files in the same location simplified things. I didn't have to worry about classpath. But not ideal as I have many files to work with.
As for the package creation, I am going to play around with java a bit more before using it. I think I need to solidify my understanding.
Thanks for helping me!
So, I have a package "com", which consists of two sub-packages "Common" and "Model1". The Model1 contains a class Model which I am trying to import in the Servlet2 class, which resides in the Common package. I compile the Model class first which stays fine, but the Servlet2 class doesn't and comes up with an error saying "package com.Model1 doesn't exist"
Here's the Model class:
package com.Model1;
import java.util.*;
**public** class Model{
public ArrayList<String> getBrands(String color){
ArrayList<String> brands=new ArrayList<String>();
if(color.equals("amber")){
brands.add("Jack Amber");
brands.add("Red Moose");
}
else{
brands.add("Jail Pale Ale");
brands.add("Gout Stout");
}
return brands;
}
}
Here's the Servle2 class:
package com.Common;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.Model1.Model;
public class Servlet2 extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("Coffee selection advice<br>");
String c=req.getParameter("color");
Model m=new Model();
ArrayList result=m.getBrands(c);
out.println("<br>Got coffee color "+c);
Iterator it=result.iterator();
while(it.hasNext()){
out.println("<br> Try: "+it.next());
}
}
}
I just can't seem to figure out how to sort this out.
Edit: Realised that default modifier is restrictive, but even making it public doesn't seem to work.
I am using notepad++ and I hope this works as the Minimal, Complete, and Verifiable example:
package com.common;
import com.model.*;
public class TheClassIWantToImportInto {
public static void main(String[] args){
System.out.println("Testing 1");
TheClassIwantToImport obj=new TheClassIWantToImportInto();
obj.testFunction();
}
}
The second class:
package com.model;
public class TheClassIWantToImport{
public void testFunction(){
System.out.println("testing function");
}
}
Both the .java files are in the same folder "C:\Program Files\Java\jdk1.8.0_161\bin"
Using the following commands in this order:
javac -d . TheClassIWantToImport.java (Works fine)
javac -d . TheClassIWantToImportInto.java (Error: package com.model doesn't exist)
Set up your project such that you have some root dir which is your project's main directory. Let's call that /Users/you/projects/MyCoolProject
Within that, make a src/main dir which will contain your sources. A source file goes in a directory that matches its package declaration. com.Model1 is a bad package name for three reasons. Convention states not to start them with caps, convention states that they are supposed to represent either your reverse website or failing that, at least the project name, and finally 'model1' is not descriptive. So let's go with package com.mycompany.coolproject.vehicleModel; instead. In that case, your Model class should be on your disk at /Users/you/projects/MyCoolProject/src/main/com/mycompany/coolproject/vehicleModel/Model.java
Use a build tool such as maven or gradle to build your project. This is going to be a lot simpler than trying to manually make javac do the right thing here. If you MUST use java, make dir build in /users/you/projects/MyCoolProject, make sure you're in that directory, and then try: javac -d build -sourcepath src/main src/main/com/mycompany/coolproject/vehicleModel/*.java and note that you'll have to add a path to that every time you make another package (to avoid having to do that... use maven or gradle).
Once you've done that, this error goes away (the error indicates that javac can't find the other source file because your project isn't properly set up yet. The above instructions lead to a properly set up project, with javac/maven/gradle being capable of finding all your source files as needed, and it's how almost all java programmers work).
I am trying to send data via usb with Java.And I decided to use the jSerialComm library. I downloaded the required jar file and imported it correctly.
The whole code :
import com.fazecast.jSerialComm.SerialPort;
public class Try{
public static void main(String[] args) throws IOException {
SerialComm ports[] = SerialComm.getCommPorts();
}
}
There is no problem with this row :
import com.fazecast.jSerialComm.SerialPort;
But there is a problem here :
SerialComm ports[] = SerialComm.getCommPorts();
Error message : SerialComm cannot be resolved to a type.
And this is advice : Create class 'SerialComm'
You
import com.fazecast.jSerialComm.SerialPort
But not
import com.fazecast.jSerialComm.SerialComm
SearialPort class is different than SerialComm, you need to import SerialComm class as well.
If you couldn't find it, it means your jar file is not compatible with your snippet code.
you should import this way :
import com.fazecast.jSerialComm.SerialComm
you could check out this if you want to more information :instalation
look at this is a example of send data via usb with Java
check out this :jSerialComm/package-summary
So I'm trying to install Jsoup to Eclipse.
Made a user library (Window->Preferences, Java->build path->user library, new->name("JsoupLibrary")->add JARs) the JARs. The JARs I downloaded from http://jsoup.org/download
Build the path to my project. (right click project->build path->configure build path, add library->user library->next->JsoupLibrary-finish)
So i tried to run the example they gave on their website (see code) I could import Document and Elements. But it keeps giving an error on "connect". Am i doing something wrong?? Does anyone know how to fix this problem?
Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method connect(String) is undefined for the type Jsoup
at JsoupTesting.Jsoup.main(Jsoup.java:12)
Jsoup test:
package JsoupTesting;
import java.io.IOException;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class Jsoup {
public static void main(String[] args) {
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements newsHeadlines = doc.select("#mp-itn b a");
}
}
Problem is that your class is also named Jsoup so compiler in this code
Jsoup.connect("http://en.wikipedia.org/")
tries to use connect(String) method from your class, not from org.jsoup.Jsoup class, and since there is no such method in your class you see the error. To remove this problem change name of your class to something else like
public class JsoupDemo {
...
}
and add import to org.jsoup.Jsoup which has method you want to invoke.
Hi I had a program which worked fine in a .jar file.
Basically all the classes were part of the same package called : "eu.floraresearch.lablib.gui.checkboxtree"
They ALL are located in the SAME "checkboxTree" folder. Each file has a line stating
package eu.floraresearch.lablib.gui.checkboxtree;
I need to modify the code and to integrate it in another project.
So I took all the .java files, copied them in my Eclipse project folder (no package anymore), and got rid of the "package eu.floraresearch.lablib.gui.checkboxtree;" line in each files. Everything is fine except for one file comprising an enumeration.
Originally the file looked like this:
package eu.floraresearch.lablib.gui.checkboxtree;
public class QuadristateButtonModel extends DefaultButtonModel {
public enum State {
CHECKED, GREY_CHECKED, GREY_UNCHECKED, UNCHECKED
}
...
}
The problem is, there is another class which originally imported the above class enumeration:
import eu.floraresearch.lablib.gui.checkboxtree.QuadristateButtonModel.State;
public class QuadristateCheckbox extends JCheckBox {
public QuadristateCheckbox() {
this(null);
}
public QuadristateCheckbox(String text) {
this(text, State.UNCHECKED);
}
...
}
First of all I find it weird how enumerations can be imported.. But it worked fine when everything was inside the package.
Since all my .java files are in the same folder now, I just removed the package line.
However I have this issue with the QuadristateCheckbox class which imports "QuadristateButtonModel.State".
If I change the import line with
import QuadristateButtonModel.State;
it states
The import QuadristateButtonModel cannot be resolved
I tried various things I found on the internet like
import static QuadristateButtonModel.State.*;
or
import QuadristateButtonModel.State.*;
but the same error messages occur:
The import QuadristateButtonModel cannot be resolved
On top of that, in the above code from QuadristateCheckbox class:
public QuadristateCheckbox(String text) {
this(text, State.UNCHECKED);
}
an error message
State cannot be resolved to a variable
which is understandable given the fact that I fail to import the State enumeration.
What can I do? Please explain to me what is wrong
PS: The code was taken from this site: http://www.javaworld.com/article/2077762/core-java/swing-based-tree-layouts-with-checkboxtree.html
The authors provide classes to build checkable trees.