package org.apache.commons.lang does not exist [Netbeans] - java

Am new to programming with basic knowledge and I've taken a liken to Java.
I wanted to write a code that calculates a number to the nth power without using loops. I've been trying to use the repeat method from "commons lang" which i came to know about, about 4 days ago. I Found a lot of info in this site and others that helped me in understanding how to use this packed.
So far I downloaded commons-lang3-3.1 then kept the folder in the same folder as my project and added the jar file to my project's library by:-
right clicking on libraries
1 then Add JAR/Folder
2 then i opened the commons-lang3-3.1 folder
3 and selected "commons-lang3-3.1.jar" from a number of 4 selections:
commons-lang3-3.1.jar
commons-lang3-3.1-javadoc.jar
commons-lang3-3.1-sources.jar
commons-lang3-3.1-tests.jar
here is a code that am using to test that i got from one of the the other questions:-
0. package refreshingmemory;
1. import org.apache.commons.lang.StringUtils;
2. public class RefreshingMemory {
3.
4. public static void main(String[] args) {
5. String str = "abc";
6. String repeated = StringUtils.repeat(str, 3);
7. repeated.equals("abcabcabc");
8.
9. }
10. }
line 1 says package org.apache.commons.lang does not exist.
line 7 says Should check the method return value
and if i remove line 1 i get a cannot find symbol at line 6
How do I get a successfully import ?
Screenshot of Netbeans:

http://commons.apache.org/proper/commons-lang/ states the following:
Note that Lang 3.0 (and subsequent versions) use a different package (org.apache.commons.lang3) than the previous versions (org.apache.commons.lang), allowing it to be used at the same time as an earlier version.
So change the package accordingly, or heed Richard Tingle's advice and left click the error+light bulb icon in the gutter (were line numbers are shown) and choose "Add import for...".
import org.apache.commons.lang3.StringUtils;

Related

Selenium Webdriver Example issue

I'm trying to follow along with the examples found on https://code.google.com/p/selenium/wiki/GettingStarted but I'm running into an issue with the package org.openqa.selenium.example being "incorrect". The rest of the code seems to be ok with the exception of the public class Example also having a red dot saying it needs to be declared, but I figured this is because the above package is having issues.
When I run the code, this is the out put:
Error: Could not find or load main class test.Test
/Users/me/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I know there is a similar thread found here :Can't run Java example for Selenium / WebDriver, but with this being my first go at using both Java and Selenium, I'm still having a hard time trouble shooting this issue. In case you don't want to follow the link to the example, here is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example {
public static void main(String[] args) {
// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new HtmlUnitDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
EDIT:
The package declaration is the package that your class Example is supposed to be in. It has to match the directory that your code is in, or else it won't compile.
Solution 1: Put your Example.java file should be in a directory like this:
[directory-to-your-project-root-or-source-folder]/org/openqa/selenium/example
Solution 2: Assuming your Example.java is already sitting directly in the root folder of your project, you can just remove the package declaration from the top of your Example.java file.
Solution 3: Declare your own package, like package com.jcmoney.example;, and then create a matching directory in your project com/jcmoney/example and put your Example.java file in it.
EDIT:
Based on the comments below and the screenshot added to the question:
See how it says "Source Packages", and below it "example" and then below it "Example.java"? Example.java is the file that your code is in. It is in the package "example".
So, quickest solution: Change your package declaration from "org.openqa.selenium.example" to just "example".
Your src package containing .java class is wrong. It should be org.openqa.selenium.example rather example. As the package declared inside class is not same as package declared outside. It threw a compile time error. Refactoring packaging to org.openqa.selenium.example outside in the src package or editing the org.openqa.selenium.example to example should fix the issue.

Execute java compiled class command line

I have the following question. Given a correctly compiled class whose source code is:
1. package com.sun.sjcp;
2.
3. public class Commander {
4. public static void main(String[] args) {
5. // more code here
6. }
7. }
Assume that the class file is located in /foo/com/sun/sjcp/, the current directory is /foo/, and that the classpath contains "." (current directory). Which command line correctly runs Commander?
A. java Commander
B. java com.sun.sjcp.Commander
C. java com/sun/sjcp/Commander
D. java -cp com.sun.sjcp Commander
E. java -cp com/sun/sjcp Commander
Answer: B
A. We are in the root dir, so we can't see the file from
/foo/com/sun/sjcp/ directly
B. is correct
C. I think is correct too ???
D. We are in /foo/com/sun/sjcp/ and there is only class file with
package package com.sun.sjcp; so the compiler can't find it.
If the file was without package declaration and was build in this dir
then it will work if we try to run it in this way.
E. The same as D - does not work
The only answer given is B. Where am I making a mistake?
C is incorrect because "com/sun/sjcp/Commander" isn't a valid class name. Path to a file and class name are not the same things.
(edited): It's appeared "that the jvm allows you to use a forward slash in place of a dot in the fully qualified name of the class to run" (but you must use only forward slashes). So it seems that C is also correct
A class name can never have forward slashes on it (it's not the same concept as a filesystem path), that's why B is the only right answer.

java - duplicate class

Confused as to why I get duplicate class error for the following code?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package database_console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* #author davidsonr
*/
public class DBConnect {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
Netbeans highlights DBConnect as red with duplicate class error.
This is a known issue with netbeans BUG 226360
it might help to clear Netbeans cache:
Go to Help -> About and you will see
Cache directory: Path\to\Directory
Close NetBeans, go to specified directory and delete everything.
This can also happen if the package name does not match the folder name, or if the package name is omitted. Check the package statement in your source.
this might be due to 2 classes with the same name in the same package
This also happens if your referencing the erroring class in a separate file in the same package, with the erroring class with an unmatching package path to the file where you are referencing erroring class.
For example
file 1
some.incorrect.path.package
class_that_is_erroring{
}
file 2
some.correct.path.package
class new_class{
class_that_is_erroring myclass = null;
}
The package paths in both files must match each other and match the file system directory.
If the file name doesn't match the class name, NetBeans 8.0.1 will report this as a duplicate class.
A new answer... In this case, the duplicate class error was confusing. So was part of the next error, but it also pointed to the real problem and the fix.
From my log file:
Error 1: a\g\GoodClass error:duplicate class: a.g.GoodClass //Not the problem
Error 2: a\b\BadClass error: cannot access GoodClass //The problem
bad source file: a\g\GoodClass //No, it's fine
file does not contain class x.y.GoodClass //How to fix it
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
Java reports the first line of Error 2 because BadClass is using a wildcarded import, either import x.*; or import x.y.*;. The java compiler found x.y.GoodClass first, so couldn't determine which you really wanted: a.g.GoodClass or x.y.GoodClass.
THE FIX: remove the wildcarded import and add the specific imports you need from library x.y.

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)

Cannot run "Hello World" program in Eclipse

I have an error in my first step with Java, so when i try to run the code hello world:
class apples{
public static void main(String args[]){
System.out.println("Hello World!");
}
}
I go to: - Run as .. -> Then i choose Java aplicacion - > And i press Ok
But when i press Ok does not appear the window down to show me the correct message Hello World
Your code works fine for me:
class apples
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
I downloaded it to c:\temp\apples.java.
Here's how I compiled and ran it:
C:\temp>javac -cp . apples.java
C:\temp>dir apples
Volume in drive C is HP_PAVILION
Volume Serial Number is 0200-EE0C
Directory of C:\temp
C:\temp>dir ap*
Volume in drive C is HP_PAVILION
Volume Serial Number is 0200-EE0C
Directory of C:\temp
08/15/2010 09:15 PM 418 apples.class
08/15/2010 09:15 PM 123 apples.java
2 File(s) 541 bytes
0 Dir(s) 107,868,696,576 bytes free
C:\temp>java -cp . apples
Hello World!
C:\temp>
Your lack of understanding and the IDE appear to be impeding your progress. Do simple things without the IDE for a while until you get the hang of it. A command shell and a text editor will be sufficient.
Sorry about missing javac; cut & paste error.
If you look at the screenshot, your class name is there, last in the list. Select it and press OK. To not see this message again, right-click on the class name on the left side and select there Run...->Java Application.
The only problem that causes your error here is that the classname and the filename do not match - and they have to.
Solution
Rename either the file thesame.java to apple.java or the class to thesame. Then if you select "Run as..." again, eclipse will present a menu item to start your Java application.
(other mentioned, that there's no requirement that a top-level class and the filename do match - unless the top level class is public. Of course this is true. But the problem was about "running" a class under eclipse as a Java application)
Try public class apples and make sure the file is apples.java. Also it should be public static void main(String[] args)
You have 2 classes by name of "thesame.java" under the source folder. Since one is directly under the src folder, and other under (default package), they use the same namespace, hence Interpreter is confused which java file to execute and is asking you to select the class you want to execute.
Class names must be capitalized... so change apples to Apples. Also, if you are a beginner (which it seems like), I would recommend the Netbeans IDE -- it's a bit more friendlier for new users than Eclipse.
You class must be named "thesame" if you store it in a file called "thesame.java", as you have. Either rename your class to "thesame" or change the file to be "apples.java".
You should move the "[]" to be before "args". So, String[] args.
Either select "apples" at the bottom of the menu you posted and run it, or right-click on the Java file and make it the default thing to run for this project. Or launch it by right-clicking on the file and selecting "run".

Categories