I wanted a program which could list all the contents available in a directory. I found a nice code in java2's.com,
http://www.java2s.com/Code/Java/File-Input-Output/ListingtheDirectoryContents.htm
And here is the code,
import java.io.File;
import java.util.Arrays;
public class Dir {
static int indentLevel = -1;
static void listPath(File path) {
File files[];
indentLevel++;
files = path.listFiles();
Arrays.sort(files);
for (int i = 0, n = files.length; i < n; i++) {
for (int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
System.out.println(files[i].toString());
if (files[i].isDirectory()) {
listPath(files[i]);
}
}
indentLevel--;
}
public static void main(String args[]) {
listPath(new File(".\\code"));
}
}
What I don't understand is the variable n in the first for loop. If it is not defined anywhere, then why is the program not showing any error?
int i, n;
would declare two ints.
In the code
int i = 0, n = files.length;
declares and initialises them.
It's declared right there, as an int. The comma separates the multiple variable declarations.
n is defined in the for loop in the same way as i.
int x,y;
Would define two variables x and y both as ints. the comma in the for with assignments just looks more complex.
Related
i use ThreadPool class and when i try to print the matrix this is what i get:
Enter number of threads:
5
Enter number of matrices:
3
Enter number diminesion:
2
[1][1][0][1]
[0][1]
-----------------------------------------------
[0][0]
[1][0]
-----------------------------------------------
[0][1]
-----------------------------------------------
i try to synchronized but is still not working good, why?
and another question, when i try to use matrices queue from GenerateMatrix class in the main is say the queue is empty what id do wrong?
because what i try to do is to generate n matrix and after the generate is finish multiply all the matrices.
main:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Queue<int[][]> matrices = new LinkedList<int[][]>();
System.out.println("Enter number of threads:");
int numOfThreads = input.nextInt();
ThreadPool pool = new ThreadPool(numOfThreads);
System.out.println("Enter number of matrices:");
int numOfMatrices = input.nextInt();
System.out.println("Enter number diminesion:");
int diminesion = input.nextInt();
for (int i = 0; i < numOfMatrices; i++) {
GenerateMatrix generateMatrix = new GenerateMatrix(numOfMatrices,
diminesion);
pool.execute(generateMatrix);
}
}
}
GenerateMatrix class:
import java.util.LinkedList;
import java.util.Queue;
public class GenerateMatrix implements Runnable {
private int numOfMatrices;
private int dimension;
private static Queue<int[][]> matrices = new LinkedList<int[][]>();
public GenerateMatrix(int n, int d) {
numOfMatrices = n;
dimension = d;
}
public Queue<int[][]> getMatricesQueue() {
return matrices;
}
public void run() {
int[][] tempMatrix = new int[dimension][dimension];
for (int i = 0; i < tempMatrix.length; i++) {
for (int j = 0; j < tempMatrix.length; j++) {
tempMatrix[i][j] = (int) (Math.random() * 2);
}
}
synchronized (this) {
for (int k = 0; k < tempMatrix.length; k++) {
for (int j = 0; j < tempMatrix.length; j++) {
System.out.print("[" + tempMatrix[k][j] + "]");
}
System.out.println();
}
System.out.println("-----------------------------------------------
");
matrices.add(tempMatrix);
}
}
}
The reason why matrices is empty in the class Main is because you never add anything to it. You create 2 variables called matrices, one in Main, one in GenerateMatrices.If you look in Main, you call:
Queue<int[][]> matrices = new LinkedList<int[][]>();
and then you never use it again, so it remains empty. If however you called GenerateMatrices.getMatrices().length, it should be non-zero (assuming you define getMatrices().
As for why it is printing weirdly, the following SO answer should help: Java: System.out.println and System.err.println out of order
In short, calls to System.out.println() are not immediately written to output, due to the high overhead of the system call. Instead, they are written to a buffer and, when the JVM is happy that more isn't going to arrive in the near future, the contents of the buffer is written to output. System.out.flush() forces this process to happen sooner, which may help you with what you need.
Alternatively, instead of using synchronized (this) {...} you can use syncrhonized (System.out) {...} to ensure no interleaving.
P.S.
GenerateMatrices.matrices probably shouldn't be static. If you create multiple instances of GenerateMatrices, you probably want them to have separate copies of matrices. And if not, you should probably create a class such as MatrixStore to make it clear what is happening.
If I have three variables and I want a value in a for loop to jump from one to the next, how would I do that? You can assume the first variable is the smallest and the third is the biggest, and that the variables are not equal to one another(although if there is a way to do it where they are equal that would be good).
I have an example for if it was only two values.
int val1 = 5;
int val2 = 9;
for(int i = val1; i <= val2; i=i+(val2-val1) {
}
In this case i would first be 5, and then 9. Also, is there any way to do it with a different amount of variables?
I'm not 100% certain I understand your question, but you could do
for(int i = val1; i <= val2; i = (i == val1) ? val2 : val2+1) {
// ...
}
If you need more values, I would put them in an array and use a for-each loop over that
int[] vals = {5,9,17};
for (int i : vals) {
// ...
}
you can place those in an array and access to it by index
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] myArray = {4, 6 , 9};
for(int x : myArray)
{
System.out.println(x);
}
//or....
for(int x =0; x<3; x++)
{
System.out.println(myArray[x]);
}
}
}
As #Gonen I said, you can handle this using stream. If you want '...the first variable is the smallest and the third is the biggest...' you should use stream.sorted() to get sorted values.
x corresponds to each one element of the vals list while traversing. So you can do whatever you want in the forEach block with using x
List<Integer> vals = Arrays.asList(5,9,17);
vals.stream().sorted().forEach(x -> {
System.out.println(x);
});
If we are already being a bit silly, this will do the trick for as many values as you want, and inside a for loop. But I would never actually write code like this because its completely unreadable:
package package1;
public class SillySkip {
public static void main(String[] args) {
for( int data[] = {5,10,-4}, i, j=0; j < data.length && (i = data[j]) % 1 == 0 ; ++j )
{
System.out.println(i);
}
}
}
From Java 8 and up you can use Stream.of to iterate arbitrary values like this:
package package1;
import java.util.stream.Stream;
public class IterateSomeValues {
public static void main(String[] args) {
Stream.of(5,10,-4).forEach(e->System.out.println(e));
}
}
I'm going through the Algorithms book by Sedgewick and I can't seem to make my IDE run their programs. The program starts but won't take the passed argument. Specifically I want it to open the tiny.txt file, which I set in Program arguments section but it's just ignored...
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
public class Selection
{
public static void sort(Comparable[] a)
{ // Sort a[] into increasing order.
int N = a.length; // array length
for (int i = 0; i < N; i++)
{ // Exchange a[i] with smallest entry in a[i+1...N).
int min = i; // index of minimal entr.
for (int j = i+1; j < N; j++)
if (less(a[j], a[min])) min = j;
exch(a, i, min);
} }
// See page 245 for less(), exch(), isSorted(), and main().
private static boolean less(Comparable v, Comparable w)
{ return v.compareTo(w) < 0; }
private static void exch(Comparable[] a, int i, int j)
{ Comparable t = a[i]; a[i] = a[j]; a[j] = t; }
private static void show(Comparable[] a)
{ // Print the array, on a single line.
for (int i = 0; i < a.length; i++)
StdOut.print(a[i] + " ");
StdOut.println();
}
public static boolean isSorted(Comparable[] a)
{ // Test whether the array entries are in order.
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
public static void main(String[ ] args)
{ // Read strings from standard input, sort them, and print.
String[] a = In.readStrings();
sort(a);
assert isSorted(a);
show(a);
}
}
You seem to want standard input redirection. Unfortunately, IntelliJ doesn't support that.
When you supply a command-line argument, all that does is that each word from the argument is passed as a string in the args argument of the main method. You can then write some code in main to open a BufferedReader on that file.
The alternative is to open a terminal window (or Command Prompt window) and type the command line java package.name.ClassName < filename.ext. The command processor or shell interprets the < character as a request to redirect standard input to the supplied file.
Alright this is what needs to be done if you want to use Algorithms code from within intelliJ IDEA on mac OS Sierra:
1, make sure to get and run algs4.app from their website
2, use intelliJ terminal to navigate to algorithms2/out/production/algorithms2 where the .class files reside
3, type in terminal: $ java-algs4 Selection < /Users/mistakeNot/Desktop/Java/algorithms2/tiny.txt
While I was attempting to make a method that runs calculations and returns the binary value for a small project I'm working on; I was trying to have the method parameters include all of the values to add together, but when doing so I realized I don't know how to do so without using an array of some sort.
Is it possible to have the parameters in the following method addBinary change based on the amount I wish to add?
public int addBinary() // I want these parameters to have all integers I wish to add
{
// Calculations go here //
}
Essentially, if I wish to run the program and add 5 values the first time and 25 the next; how would I get all of the values into the method without creating an array?
You can use variable number of arguments in the method definiton(using ellipses i.e ... ) like this:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int add(int ...arr)
{
int sum=0;
for(int i=0;i<arr.length;i++)
sum+=arr[i];
return sum;
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(add(1, 2, 3, 4));
System.out.println(add(1, 2, 3));
}
}
Output:
10
6
https://ideone.com/PHL8Lb
I don't know why you are not thinking of using arrays here. Just pass an array as a parameter and do the calculations you want to do.
public int addBinary(int a[])
{
for(int i=0;i<a.length;i++)
sum+=a[i];
return sum;
}
Or by using an arraylist
public int addBinary(ArrayList m)
{
int sum = 0;
for(i = 1; i < m.size(); i++)
sum += m.get(i);
return sum;
}
Link for the code Ideone
You can use varargs for this
void testapp(String ...studentsName){
for (int i = 0; i < studentsName.length; i++) {
System.out.println(studentsName[i]);
}
}
This code supposedly checks an array of integers for 9's and returns it's frequency but the method is not being recognized. Any help please to make this code work.
public static int arrayCount9(int[] nums) {
int count = 0;
for (int i=0; i<nums.length; i++) {
if (nums[i] == 9) {
count++;
}
}
return count;
};
public static void main(String[]args){
System.out.println(arrayCount9({1,2,9}));
}
Change your method call to the following:
System.out.println(arrayCount9(new int[]{1,2,9}));
Alternatively:
int[] a = {1,2,9};
System.out.println(arrayCount9(a));
The shortcut syntax {1,2,9} can only be used when initializing an array type. If you pass this notation to a method, it will not be interpreted it as an array by the compiler.