Java - Indenting the line each time a for loop runs - java

I am writing a method to list all the files in a directory but I can not figure out how to make each subdirectory have one more tab than the last one.
Here is my code:
private static void recurseDirectoryHelper(File rootDirectory){
File[] list = rootDirectory.listFiles();
if (rootDirectory.isDirectory()){
for (int f = 0; f < list.length; f++){
if (list[f].isFile()){
System.out.println("\t" + list[f].getName());
countFiles++;
}
}
for (int d = 0; d < list.length; d++){
if (list[d].isDirectory()){
System.out.println("Subdir: " + list[d].getName());
recurseDirectoryHelper(list[d]);
}
}
}
//System.out.println("Total Files: " + countFiles + "\t" + "Total Directories: " + countDirs);
}

Add another parameter to your function called count, like so:
private static void recurseDirectoryHelper(File rootDirectory, int count){
Each time you recursively call your function, pass count + 1, like so:
recurseDirectoryHelper(list[d], count+1);
Then when you do your System.out.println, you know exactly how many tabs to do.

I would simply add a tabSpace string parameter in the recursion method to avoid unnecessary looping inside as:
private static void recurseDirectoryHelper(File rootDirectory, String tabSpace){
In first call, I would pass tabSpace as empty String ("") or single tab("\t") as desired and then with-in the recursive calls for sub-directory, simply pass tabSpace+"\t" as
recurseDirectoryHelper(list[d], ""); //<-- First call from outside
recurseDirectoryHelper(list[d], tabSpace+"\t"); //<-- recursive calls
While printing the list, simply use the tabSpace for indentation:
System.out.println(tabSpace + list[f].getName());

Have a second parameter to store the level at which your method has recursed. When it's first called, it will be zero. When you call the method recursively, pass in level + 1.
When printing, use level as the number of tabs to print.

private static void recurseDirectoryHelper(File rootDirectory, String indent){
if (rootDirectory.isDirectory()){
File[] list = rootDirectory.listFiles();
for(File file : list) {
if (file.isFile()){
System.out.print(indent);
System.out.println(file.getName());
}
}
for(File file : list) {
if (file.isDirectory()){
System.out.print("Subdir: ");
System.out.println(file.getName());
recurseDirectoryHelper(file, indent + indent);
}
}
}
}

Related

How to iterate a condition in a while loop? Beanshell

Edited from my original post because I found a work around.
I'm trying to use a while loop to check if inputs exist. I have inputs that can vary in size, meaning I can have one input in a case or multiple in another. I'm using a while loop to execute many lines of code if the input(s) are present. The issue is that I know that I'll have at least one input in a case but in another case I may have 5,6,7, etc.
For example if I have:
input0="taco";
input1="water";
input2="sand";
With the example above in mind how do I iterate the condition of the while loop to make sure input0, input1, and input2 get executed?
In this example all of the commands within the while loop would be executed as long as input0,1,2 exist and are defined. My hope is that the integer q will scale with each input and the code within the while loop executes based on the current input.
When the loop reaches input3 I'd like it to exit the loop because that input does not exist.
I currently have the following:
int q=0;
String inputV =input(q);
while(inputV.contains("~")){ //first iteration takes "taco"
//This is where my long lines of code that need to be executed are
// I'm hoping that q will populate with 0,1,2 as the loop goes on and take "taco" "water" "sand" respectively
q++;
inputV=input(q);
//The next iteration will be input(1) = input1 which is "water"
}
New edit given the comment from Roger. The execution is having trouble getting through the if(f.equals(field)) statement. It passes through the for loop but can't process the if statement.
String input(int q) {
String field = "input" + q;
for (String f: global.variables) {
if (f.equals(field)) {
return (String) this.namespace.getVariable(field);
}
}
return null;
}
int q=0;
String inputV = input(q);
while(inputV != null) {
print(q + " " + inputV);
print("The input parameter is not null");
print("The input value is " + inputV);
// long lines of code executed within the while loop
q++;
inputV=input(q); }
You can find the defined variables in this.variables, global.variables or via the namespace.getVariableNames(). So with a helper method it is possible. In the example below I assumed they are defined in the global space.
input0="taco";
input1="water";
input2="sand";
String input(int q) {
String field = "input" + q;
for (String f: global.variables) {
if (f.equals(field)) {
return (String) this.namespace.getVariable(field);
}
}
return null;
}
int q=0;
String inputV = input(q);
while(inputV != null) {
System.out.println(q + " " + inputV);
q++;
inputV=input(q);
}
But, isn't there a better way for you to define the values such as array or list?

Iteration is not writing on the right Array Index

I found a code that iterates trough a folder and return the fileNames.
I created a String[] Array with 8000 positions, since I have around 7500 files and getting more.
If I use the code that I found with system.out.println it returns every single file name, but if I use my code to write the position into the Array index, I only get 1 position and rest full of null.
Unlucky I cannot figure out the problem.
import java.io.*;
public class Tester {
public static void main(String[] args) {
File folder = new File("mypath\\myfilefolder");
File[] listOfFiles = folder.listFiles();
String[] fileNames = new String[8000];
for (int i = 0; i < listOfFiles.length; i++) {
int c = 0;
if (listOfFiles[i].isFile()) {
fileNames[c++] = listOfFiles[i].getName();
// Seems not to be doing anything like supposed
// System.out.println(listOfFiles[i].getName());
// Prints every filename on a new line
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
for (String element: fileNames) {
System.out.println(element);
}
}
}
I expect to be able to iterate trough fileNames and get the filesNames so I can work with it.
But actually only the first positions get changed, all the others are still null.
The value changed at 'c++' is never used. Every time before your code execute to c++ the variable of c being reset to 0.
And this would be the same algorithm with the use of the stream API (Java 1.8 and above):
String[] fileNames = Arrays.stream(folder.listFiles()) // stream all the files in the directory
.filter(file -> !file.isDirectory()) // filter any directory files in there
.map(File::getName) // map an item to its name
.toArray(String[]::new); // collect as a String array

I want to compare an arrayList object with a String, ignoring case. How can I do this?

Following code written in Java
public static void main (String [] args) throws Exception
{
ordListe ol = new ordListe();
ol.lesBok("navn.text");
ol.leggTilOrd("hello");
ol.leggTilOrd("Hello");
Is my main method. This is about reading from file and adding to a arraylist(dictionary). ''Hello'' and "hello" is supposed to be the same word, and in the code under, it should increase the count of that word.
for (int i = 0; i < ordListe.size(); i++)
{
if (ordListe.toString().contains(s))
{
if (ordListe.get(i).toString().equalsIgnoreCase(s))
{
ord.oekAntall();
System.out.println("'" + s + "' That word is found and there are " + ord.hentAntall() + " of that word now in dictionary.");
break;
}
}
else
{
Ord ny = new Ord(s);
ordListe.add(ny);
System.out.println("'" + s + "' This word is added. " + ny.hentAntall() + " of this word in dictionary.");
break;
}
}
So this is a part of my code. From the main method I add words like ol.leggTilOrd("hello"); leggTilOrd is my method where the code right above is taken from. This is the part of the code that adds words to the dictionary/arrayList and checks if inputwords already exists. I have no problem with anything else than the specific if (ordListe.get(i).toString().equalsIgnoreCase(s)) part. If a word exist in the arrayList, I'm supposed to increase the count of that word. If not, I add the word in the arraylist (ordListe). The problem is that even if I add ol.leggTilOrd("hello") or ol.leggTilOrd("Hello"); with capital 'H', I can't get to recognize it as the same word even if I use the statements above. How do I do this, any other possibilites? This is my last possible effort, after many attempts earlier.
If there are anything questionable above, just tell me.
Change both strings to lower case before comparing and then comapare..it will help you and is easier!!! Use toLower function and then compare
The problem is this line:
if (ordListe.toString().contains(s))
Because 1) you do not compare the lowercase or uppercase versions of the two strings and 2) you probably not overrided toString so it returns the items in the list as you probably expect. Put this function in your ordListe class assuming that your ordliste extends arraylist:
public boolean containsIgnoreCase(String item) {
for(int i = 0; i < size(); i++) {
if (get(i).toString().equalsIgnoreCase(item)) {
return true;
}
}
return false;
}
Now you can call containsIgnoreCase to determinate if there is a specific item in the list ignoring the case

return a series of print statements within a for loop

I have a class which contains an array list of which the user will enter its elements. I think I can successfully add elements to this array list but I cannot tell as I cannot output the array list. I want to call the method viewNYC in the main programme and for it to display a list of its elements in cmd prompt. Can any one help?
import java.util.*;
class Hotels{
public static ArrayList NYC = new ArrayList();
public static String[] NYCArray = (String[])NYC.toArray(new String[NYC.size()]);
public static void addNYC(String hotel){
String NYChotel = hotel;
NYC.add(NYChotel);
}
public static void viewNYC(){ //Will be called in main programme
for(int i=0; i< NYCArray.length; i++){
return System.out.println(i+1 + ") \t" + NYCArray[i]);
}
}
}
The return type of viewNYC is void. Remove the return keyword in your for loop:
for (int i = 0; i < NYCArray.length; i++) {
System.out.println(i + 1 + ") \t" + NYCArray[i]); // no "return"
}
Is your program compiling becuse it should through a compile error(Void methods cannot return a value) at
return System.out.println(i+1 + ") \t" + NYCArray[i]);
because
System.out.println()
doesnot return anything. If you want to print an array use
System.out.println(Arrays.deepToString(NYCArray));
First of all, remove the return statement from the sysout:
System.out.println(i + 1 + ") \t" + NYCArray[i]);
in addition, if I read your code I can see that you have a static String[] NYCArray which will not be updated in your code example.
So if you addNYC a hotel, it will not be visible in NYCArray, this update should be done at the end of the addNYC
(Create a new Array with the new size of the ArrayList and set the content to your ArrayList's content)
You are indeed adding elements to NYC, but those changes will not be reflected in NYCArray.
The line:
public static String[] NYCArray = (String[])NYC.toArray(new String[NYC.size()]);
will declare NYCArray as an array of Strings, and set its initial value to an array "copy" of NYC. However, the line will only run once, and at that point NYC is still empty!
If you want to print the contents of NYC, do something like:
System.out.println(Arrays.toString(NYC.toArray()));
Unless you have a very good reason for keeping it, I would get rid of NYCArray entirely.

Printing array error

This is probably a simple fix, but I am just not seeing it. I am trying to figure out, how do I get my printOut() method to print properly from the main Project5PartA? Do I need get, set, and return methods? Also, is my while loop even necessary in the Tester class?
The program compiles and keeps running to infinity, so I guess the while loop is wrong. But it also only prints out [Ljava.lang.String;#7c1c8c58 continuously on each line.
The classes that extend the main are irrelevant and part of the project. Apologies if this was posted wrong and thanks for any help.
The output of the whole program would be similar to:
Bark, bark.
Meow, meow.
Roooaaar.
Dog says woof, woof.
Cat says meow, meow.
Tester Class:
public class Tester {
String[] animalArray = {"Dog", "Cat", "tRex", "Cow", "Pig", "Snake",
"Goat", "Owl", "Chicken", "Frog"};
String[] noiseArray = {"Woof, woof", "Meow, meow", "Roooaaar", "Mooo",
"Oink, oink", "Hissss", "Baaa", "Hoot, hoot", "Bock, bock",
"Ribbit, ribbit"};
String[] printArray = new String[10];
public String printOut() {
while (true) {
for (int i = 0; i < 10; i++) {
String value = (animalArray[i] + " says " + noiseArray[i] + ".");
printArray[i] = value;
System.out.println();
System.out.println(printArray);
break;
}
}
}
}
Use Arrays.toString() to print the contents of an array. Don't actually print the array itself.
System.out.println(printArray); // Prints [Ljava.lang.String;#7c1c8c58
System.out.println(Arrays.toString(printArray0); // Prints [Dog says Woof, woof...]
If you do use Arrays.toString(), print the array outside the loops.
You could also just print each part of the array with System.out.println(printArray[i]) inside the loop.
public String printOut() {
while (true) {
for (int i = 0; i < 10; i++) {
String value = (animalArray[i] + " says " + noiseArray[i] + ".");
printArray[i] = value;
System.out.println();
System.out.println(printArray[i]); // This works
break;
}
}
System.out.println(Arrays.toString(printArray); // Also works
}
Because printArray is array and doesn't have a toString() method you will have to print out each element seperatly or use Arrays.toString(printArray) method.
Something like this will get you a growing array if it's in the while loop. Place it outside the while loop:
System.out.println(Arrays.toString(printArray));
Or in the while loop:
System.out.println(printArray[i]);
You don't need the while loop unless you really want your program to run forever.
You should change your print statement as follows. (You were printing the array object, not the array contents.)
System.out.println(printArray[i]);

Categories

Resources