Create a class instance - java

I am just starting to use Java. I am using NetBeans and inside my .pkg1 file I have two .java files. I am doing the Coursera course on Algorithms by the way, so my code references that:
CourseraAlgorithmsWeek1.java
package coursera.algorithms.week.pkg1;
public class CourseraAlgorithmsWeek1 {
public static void main(String[] args) {
QuickFindUF mystuff(10); // DOES NOT WORK!
}
}
QuickFindUF.java
public class QuickFindUF {
private int[] id;
public QuickFindUF(int N){
id = new int[N];
for(int i =0; i< N; i++){
id[i] = i;
}
}
}
My problem is that the first line in my main function does not recognize the QuickFindUF object creation. I read that I need to compile the second file into a .class file, and then into a .jar file. How can I do this with netbeans?
I also read a bit about the Classpath. Can I only add .jar files to the classpath?

change
QuickFindUF mystuff(10);
to
QuickFindUF mystuff = new QuickFindUF(10);

Move QuickFindUF.java to the same package of your main class by adding
package coursera.algorithms.week.pkg1;
before class definition.

You can add a directory to the classpath as well. You could do something like
export CLASSPATH = "."
and that would include the directory you are currently in. This should allow you to compile and execute code in that directory.
If the classpath is set correctly, you can either move the QuickFindUF class to the coursera.algorithms.week.pkg1 package by adding this declaration at the top of the page:
package coursera.algorithms.week.pkg1;
or, you can import the class by using the declaration:
import coursera.algorithms.week.pkg1.CourseraAlgorithmsWeek1;

1. Use Composition.
QuickFindUF q = new QuickFindUF();
q.mystuff(10);

Related

Java Path Finder NumericValueChecker

I am trying to learn Java Path Finder (JPF). I downloaded the JPF and build it. Currently I have jpf-core folder which has example .java files together with their corresponding .jpf files. My goal is to create a new basic .java file and check whether a specific value in this file exceeds the max-bound I specified in the .jpf file.
In the examples folder there is .java file called NumericValueCheck.java which is exactly what I want, and it works as expected. (finds when the value exceeds the bound)
NumericValueCheck.java
public class NumericValueCheck {
public static void main (String[] args){
double someVariable;
someVariable = 42;
someVariable = 60;
}
}
NumericValueCheck.jpf
target = NumericValueCheck
listener = .listener.NumericValueChecker
# NumericValueChecker configuration
range.vars = 1
range.1.var = NumericValueCheck.main(java.lang.String[]):someVariable
range.1.min = 0
range.1.max = 42
However, I created a new .java file and named it "BasicCheck.java". Here is the code inside it;
public class BasicCheck {
public static void main(String[] args){
double result;
result = 60;
result = 110;
}
}
Here are the properties in BasicCheck.jpf;
target = BasicCheck
listener = .listener.NumericValueChecker
# NumericValueChecker configuration
range.vars = 1
range.1.var = BasicCheck.main(java.lang.String[]):result
range.1.min = 0
range.1.max = 60
I compiled the BasicCheck.java using javac BasicCheck.java in a separate directory. Then I copy "BasicCheck.java" and "BasicCheck.jpf" to examples folder of jpf-core where NumericValueCheck.java and NumericValueCheck.jpf also in the same place. I also copy "BasicCheck.class" to jpf-core/build/examples directory where "NumericValueCheck.class" also in the same place.
However, when I run the command java -jar build/RunJPF.jar src/examples/BasicCheck.jpf, it can't find any error. The result is "no error detected". It should detect 110 which is bigger than the upper bound 60.
Why is it not working? Do I need to add something extra to my new BasicCheck.java or BasicCheck.jpf ?
Thanks in advance.
I found the solution after a long effort. The solution is simple.
Put BasicCheck.java and BasicCheck.jpf under the directory jpf-core/src/examples.
Do NOT compile to source using javac. Open the terminal and cd to jpf-core directory. Then type the following command: ./gradlew buildJars.
That's it. Now you can use the command java -jar build/RunJPF.jar src/examples/BasicCheck.jpf to run Java Path Finder.

running .class files with java.exe - Error: Could not find or load main class

code:
package pack1;
public class Demo01 {
public void run() {
System.out.println("--running Demo01--");
demoMethod1();
}
private void demoMethod1() {
int foo = 5;
int bar = 10;
int res = foo+bar;
System.out.println("res: "+res);
}
public static void main(String[] args){
Demo01 demo01 = new Demo01();
demo01.run();
// new change...
Demo02 demo02 = new Demo02();
demo02.run();
}
}
rest can be found here: https://code.google.com/p/ci-research-teamcity-test-project/source/browse/#svn%2Ftrunk%2Fsrc%2Fpack1
I'm trying to run the .class files with java.exe through the command line to no avail.
Yes I've looked for solutions, tried running the root folder with the -cp flag but I keep getting the same error. Works just fine in Eclipse.
Ok, we have several points to note at this point.
The class is in a package. Thus, it must be in a folder names exactly as the package name ("pack1" in your case).
Your folder structure must be like this:
"root folder" (X)
| pack1
| Demo01.class
| Demo02.class (as I just noticed that you are also referring to it in the code)
Then, in order to start it, you have to be in the parent folder (this has to be the current working directory; marked with X) of "pack1" and execute
java pack.Demo01
Note, you have to use the whole canonical class name for referencing it, without .class at the end.
If you don't want or cant change the current working directory to the "root folder" you can use -cp PATH as first parameters to java.exe.

How can I compile code that uses a .jar file class with BlueJ?

I am learning java with BlueJ, and recently I was given a .jar file called Imagen.jar. Apparently, what it does is return some pixel vectors depending on image file names given as parameters to it.
Anyway, I am supposed to make a program that will use a class called Imagen. Apparently, such class is within the mentioned .jar file.
Clearly, BlueJ won't compile if I'm using such class since I have not imported it or anything. But, I don't really know how to import such class in the first place.
I was given the following example code:
import java.io.PrintWriter;
public class Main {
public static void main(String arg[ ]){
if(arg.length > 1){
Imagen imagen = new Imagen(arg[0]);
int [][] m = imagen.getMatriz();
PrintWriter salida = null;
try {
salida = new PrintWriter(arg[1]);
}
catch(Exception e){
System.err.println(e);
}
for(int [] fila : m ){
for(int valor : fila){
System.out.print("\t"+valor);
salida.print("\t"+valor);
}
salida.println("");
System.out.println("");
}
if(salida!=null){
salida.close();
}
}
else {
System.out.println("Uso: java -classpath .;Imagen.jar Main nombreArchivo.gif");
}
}
}
Which does not compile using BlueJ. However, as you can see, at the end it says that to use it, you have to type in the terminal:
java -classpath .;Imagen.jar Main myImageFile.gif
And I do it. But it keeps throwing me the same message.
So I am stuck right now:
Why is the terminal line I was told to use not working?
How can I import the class that is contained within a .jar file?
You need to do the following once.
Select the menu option Tools -> Preferences.
In the resulting dialog, click on the Libraries tab.
Click the Add button.
Navigate to the folder containing jar file. Select jar file.
Restart BlueJ.
Answer extracted from this place
you need to import Imagen class as it is being used in the main method.

Get the number of files in a folder, omitting subfolders

Is the any way to get the number of files in a folder using Java?
My question maybe looks simple, but I am new to this area in Java!
Update:
I saw the link in the comment. They didn't explained to omit the subfolders in the target folder.
How to do that? How to omit sub folders and get files in a specified directory?
Any suggestions!!
One approach with pure Java would be:
int nFiles = new File(filename).listFiles().length;
Edit (after question edit):
You can exclude folders with a variant of listFiles() that accepts a FileFilter. The FileFilter accepts a File. You can test whether the file is a directory, and return false if it is.
int nFiles = new File(filename).listFiles( new MyFileFilter() ).length;
...
private static class MyFileFilter extends FileFilter {
public boolean accept(File pathname) {
return ! pathname.isDirectory();
}
}
You will need to use the File class. Here is an example.
This method allows you to count files inside the folder without loading all files into memory at once (which is good considering folders with big amount of files which could crash your program), and you can additionaly check file extension etc. if you put additional condition next to f.isFile().
import org.apache.commons.io.FileUtils;
private int countFilesInDir(File dir){
int cnt = 0;
if( dir.isDirectory() ){
Iterator it = FileUtils.iterateFiles(dir, null, false);
while(it.hasNext()){
File f = (File) it.next();
if (f.isFile()){ //this line weeds out other directories/folders
cnt++;
}
}
}
return cnt;
}
Here you can download commons-io library: https://commons.apache.org/proper/commons-io/

Android Java - Putting all file names from R.raw into array without manually specifying each

There are 2 parts to my question but both are related. I have searched all over the place but cannot find a way to put in an array, all file names from R.raw, such as MP3s in string format.
I also want to create new buttons on the fly in Java, as opposed to using the XML files to lay out buttons.
psuedocode:
array[] = put all file names from R.raw into this array with file name;
count = count num of rows in array[];
//I want to be able to do this with that array
for (int i = 0; i < count; i++) {
create new button and assign it a sound(onclick);
this.button should be placeable anywhere i want without using XML for layout
}
Thanks in advance to any help anyone can provide!
Short answer: You can't.
Long answer: R.raw and the likes are generated at build time, thus static in your code (you can't dynamically add entries to these objects from your app). Basically, R is just a class that looks something like:
package com.yourapp;
public class R {
public class raw {
public static final int file_1 = 123456; // where 123456 is the address where that file will be found
public static final int file_2 = 789012;
// ...
}
}
Thus, there's no way (that I know of) of getting an array of these attributes.
I recommend you use the assets/ directory instead of R.raw. This way, you'll be able to use AssetManager.list() to get a list of files (and the other AssetManager functions for actually working with the files).
You can use reflection:
Field [] f=R.raw.class.getFields();
for (Field field : f) {
field.getName();
}

Categories