I have a main class which has an ArrayList. This ArrayList has a set of values stored via iteration. I need to use this ArrayList (fileList & directoryList) value in another class. How can I achieve this?
I do not want to move the ArrayList into another class.
package com.filehandler;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileFinder {
public static void main(String[] args) {
// TODO Auto-generated method stub
int directoryCount = 0;
/* Declare Lists for Files & Directories */
List<String> fileList = new ArrayList<String>();
List<String> directoryList = new ArrayList<String>();
// enter code here
/* Set file location */
File myFolder = new File("O:\\The Ultimate Book Shelf\\Technical");
File[] myFileList = myFolder.listFiles();
/* Iterate the folder to get the details of Files & Folders */
for (int count = 0; count < myFileList.length; count++) {
if (myFileList[count].isFile()) {
// System.out.println("File " + myFileList[count].getName());
fileList.add(myFileList[count].getName());
} else if (myFileList[count].isDirectory()) {
directoryCount++;
// System.out.println("Directory " +
// myFileList[count].getName());
directoryList.add(myFileList[count].getName());
} else {
System.out
.println("There are no files or directories in the mentioned path. Please verify the folder location.");
}
}
System.out.println("Total Files : "
+ (myFileList.length - directoryCount));
System.out.println("Total Directories :" + directoryCount);
System.out.println(fileList);
System.out.println(directoryList);
}
}
Your other class can either accept two ArrayLists in its own constructor or as parameters for a specific method, depending on what you are trying to do. By passing them as parameters you will actually pass a reference to the ArrayLists you created in you main function, therefore the other class will be able to read the values inside.
It depends how would the array be used in the second class. You have the following options.
To use the array in a method in the second class.
To use the array as a member in the second class.
To use the array as a static member in the second class.
For 1, you can simply pass the array to the method.
For 2, you can pass the array to a constructor and initialize the member variables in the class.
For 3, you can set like SecondClass.fileList = myFileList;
Related
This is regarding a Java homework assignment:
I want to create a method that takes the list of cards as a parameter and prints all the cards to the screen. Each card should print all stored information so that I can use the newly created method to print all the cards. And it is required for me to use the Array list of Card objects as a parameter.
I have three class in this program, namely - Main.java, HandDrawn.Java, and Card.java. Basically the program tracks the Christmas card information with the sender's name and if they are hand written or not. I'm stuck at this point as I don't know how to use ArrayLists properly and pass them through a method in order to print them.
public class Main {
public ArrayList<Card> cardsList = new ArrayList<>();
public static void main (String [] args){
Main myApp = new Main();
}
public void printAll (ArrayList<Card> cardArrayList){
System.out.println(cardArrayList);
HandDrawn sender1 = new HandDrawn("Anna", true);
HandDrawn sender2 = new HandDrawn("Kalle", false);
cardsList.add(0, sender1);
cardsList.add(1, sender2);
}
public void printing(ArrayList<Card> cardsList) {
System.out.println(cardsList);
}
}
Please see this examples:
how to print ArrayList in java
System.out.println("Print Arraylist using for each loop");
for( String strDay : aListDays ){
System.out.println(strDay);
}
Your logic does print the List before ot has anything in it. Try adding something to the List before printing the content.
public void printAll (ArrayList<Card> cardArrayList){
System.out.println("List content: " + cardArrayList.toString()); // <- Empty List at this point
HandDrawn sender1 = new HandDrawn("Anna", true);
HandDrawn sender2 = new HandDrawn("Kalle", false);
cardsList.add(0, sender1);
cardsList.add(1, sender2);
}
The output is then:
List content: []
For this program I'm supposed to read from a txt file containing information on the automobile's make, model, mpg, and trunk space in that order. An example is:
hyundai
genesis
24.6
100
and repeated for several different cars.
We had to construct an "Automobile" superclass with the instance variables of make and model. Then a "GasEngineAuto" subclass with instance variable for mpg that extends "Automobile". Then a subclass called "Sedan" that extends "GasEngine
Auto" and has instance variable for trunk space. For the assignment we had to get these classes signed off on to make sure that they made correctly.
Write a method to read the information from the file gas_sedans.txt and store it in the list you created in the previous step. The list should be the only parameter for this method. Within the method, open the file, read the information for each sedan into appropriately-typed variables, call
the parameterized constructor (the one that takes arguments for all attributes) to create the object, then add the object to the list. Call this method from main.
Below is my code so far. I wanted to try to make sure I could read into the arrayList before I used a method to do it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author
*/
public class lab10_prelab {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Sedan> sedanList = new ArrayList<Sedan>();
File myFile = new File(System.getProperty("user.dir")+"/src/gas_sedans (1).txt");
if (!myFile.exists()){
System.out.println("The file could not be found");
System.exit(0);
}
Scanner inputFile = new Scanner(myFile);
while (inputFile.hasNext())
{
Sedan a = new Sedan();
a.setMake(inputFile.nextLine());
a.setModel(inputFile.nextLine());
inputFile.nextLine();
a.setMPG(inputFile.nextDouble());
inputFile.nextLine();
a.setTrunkCapacity(inputFile.nextDouble());
sedanList.add(a);
}
inputFile.close();
}
}
It says that I get a InputMismatchException notice when I try to run the program.
You have typo error:
automobileArray and autombileArray are different.
In your code you are missing o after m in the variable
autombileArray
^
Edited: 06:49am 18/07/20115
It says that I get a InputMismatchException notice when I try to run
the program.
a.setModel(inputFile.nextLine());
inputFile.nextLine();//remove this line
a.setMPG(inputFile.nextDouble());
inputFile.nextLine();
a.setTrunkCapacity(inputFile.nextDouble());
inputFile.nextLine();//add here
I made some changes and arrived at this. Now it says to: Write a method to display the list. The method should have one parameter, an ArrayList of Automobiles. Within the body of the method, call upon the toString method to display each item. Call this method at the end of main. Does this mean make a class like "public String toString()...
or is what I did fine.
public class Smith_lab10_prelab {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Automobile> AutomobileList = new ArrayList<Automobile>();
fillAutomobileList(AutomobileList);
displayAutomobileList(AutomobileList);
}
public static void fillAutomobileList(ArrayList sedanList) throws FileNotFoundException {
File myFile = new File(System.getProperty("user.dir") + "/src/gas_sedans (1).txt");
if (!myFile.exists()) {
System.out.println("The file could not be found");
System.exit(0);
}
Scanner inputFile = new Scanner(myFile);
for (int i = 0; inputFile.hasNext(); i++) {
Sedan a = new Sedan();
a.setMake(inputFile.next());
a.setModel(inputFile.next());
a.setMPG(inputFile.nextDouble());
a.setTrunkCapacity(inputFile.nextDouble());
sedanList.add(a);
}
}
public static void displayAutomobileList(ArrayList automobileList) {
System.out.println(automobileList.toString());
}
}
I have an array I created that holds the contents of a file. This array is not in my main method, but another method. I am having trouble figuring out how to copy the array holding the file contents into an array within my main method so I can manipulate/append the information from there. I'm getting an error saying that it can't find the variable dataPieces. Can someone please help me figure this out? Is this even the best way to work with a file so that I can show the user the information and let them append it?
Thanks
/**
Add in javadoc comments
*/
//import statements
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Try {
public static void main(String[] args){
String dataHolder[] = createFile();
System.out.println(dataHolder);
}
public static String[] createFile(){
//create file holding inventory information
String dataPieces[] = new String[10];
try{
PrintWriter outputFile = new PrintWriter("inventory.txt");
outputFile.println("3000.0");
outputFile.println("Lamps 15.3 400");
outputFile.println("Chairs 19.95 250");
outputFile.print("Desks 95.0 300");
int i =0;
outputFile.close();
File myFile = new File("inventory.txt");
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext() && i<dataPieces.length){
dataPieces[i] = inputFile.next();
i++;
}
inputFile.close();
}
catch(IOException e){
System.out.println("File cannot be created."); //what to say???????????<<<<<<<<
}
return dataPieces;
}
}
Your createFile() method already returns an array, so your main method should just assign that array to a variable :
public static void main(String[] args){
String[] dataHolder = createFile();
...
}
There's no reason to call createFile() multiple times.
You have something like:
for(int i=0; i<dataHolder.length; i++){
dataHolder[i] = createFile(dataPieces);
}
Here you are trying to create inventory.txt file 10 times after that reading the same 10 times in a loop as above which is going to return you the same data.
So your method createFile is returning an array i.e. dataPieces, you could just change your for loop to something like:
dataHolder = createFile();
for(int i=0; i<dataHolder.length; i++){
...do something with dataPieces which is referred by dataHolder now.
}
There by reading and writing file just once and then operating on array further in another method.
I am studying Java and using BlueJ so my question relates to part of an assignment I have been asked to do. Some of it works but I am having problems with other parts. I will include everything that I have done in the class so far but first here are the requirements:
Prompt user to select an appropriate file // done and working
Use BufferedReader and Scanner objects to read a file line by line // done and assume working!
As each line containing the name and age of a runner is read, a new Runner object should be created and its instance variable set as follows: // Class Runner already created
// Class MathatonAdmin - current class.
3a) name - can be set directly using the value from the file.
// tested with System.out.println and all values (in display panel) are shown (*).
3b) ageGroup - can be worked out from the given age: runners under 18 should be categorised as junior, 55 and older as senior, all else as standard.
// tested with System.out.println and all values (in display panel) are shown (*).
3c) The instance of Runner should be added to the list referenced by the instance variable runners.
Essentially when I run the test code provided:
MarathonAdmin ma = new MarathonAdmin();
ma.readInRunners();
I am supposed t o see a list of runners when I inspect ma; currently one the name and age of a single person is listed.
So I need help with 3a - 3c. How do I create a new instance of Runner with said variables, then add the instance Runner to the list in runners?
I have tried a for loop in while loop but since I am guessing the for loop I do not get the required list in the variable ma.
I am using System.out.println for testing that I at lest have the correct file.
Any help or advice will be appreciated.
The class MarathonAdmin:
import java.util.*;
import java.io.*;
import ou.*;
/**
* MatharthonAdmin Class
*
* #author Stephen Berry
* #version 28/03/14
*/
public class MarathonAdmin
{
// instance variables
private String runners;
private String age;
/**
* Constructor for objects of class MarathonAdmin
*/
public void MarathonAdmin()
{
List<String> runners = new ArrayList<>();
}
public void readInRunners()
{
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
BufferedReader bufferedFileReader = null;
try
{
String currentLine;
Scanner lineScanner;
bufferedFileReader = new BufferedReader(new FileReader(aFile));
currentLine = bufferedFileReader.readLine();
while (currentLine != null)
{
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
runners = lineScanner.next();
age = lineScanner.next();
for (String aList: runners)
{
Runner runners = new Runner();
if (Integer.parseInt(age) < 18)
{
System.out.println(currentLine + " : Junior");
}
if (Integer.parseInt(age) > 55)
{
System.out.println(currentLine + " : Senior");
}
if (Integer.parseInt(age) > 18 && Integer.parseInt(age) < 55)
{
System.out.println(currentLine + " : Standard");
}
currentLine = bufferedFileReader.readLine();
}
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
}
There are some points in your class that lead to this missbehaviour of your program.
The Exercise says that you shall create a list of runner objects as instance variable right? Look at your instance variable runners of your marathon class and look at the type of it. ;)
Your while loop is a good approach. Now inside the while loop you interate for each line of the textfile which is equivalent to one runner right? So why you need the for loop? You can use the lineScanner to get each part of the line there is no need for a second loop i try to give you a structure with pseudocode
String runnerName;
Int runnerAge;
while (currentLine != null)
{
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
runnerName = lineScanner.next();
runnerAge = lineScanner.next();
runners = lineScanner.next();
age = lineScanner.next();
create new Runner Object
set age and name of object according to the data you ve just read
runners.add(Runnerobject) // <-- this line adds the object you ve just created to the list which is your instancevariable. Make sure that this variable really is a list :)
currentLine = bufferedFileReader.readLine();
}
}
Hope this helps you a little bit.
You create a Runner instance, but you don't set the instance variables name and age/ageGroup for class Runner. You could create a constructor in the Runner class to do that. Also you should rename your variable, since runners is already used.
Further you declared runners as an instance variable of type String. But you would need to have a List. After you created the Runner instance you can add that instance to the list.
Your instance variables are incorrect. You need a list of objects not a String runners.
Also you need a method instance for age not a class instance.
private List<Runner> runners; // instance variables for a list of runner objects
runners = new ArrayList<Runner>(); // in the constructor
I would also agree with MeiSign, you do not need a for loop within the while loop
I have try many things, and I am so stuck in this problem.
I have to read from a text file, and throw it inside an arraylist in a private method.
And then make a new method that will print the arraylist out.
This is what I have tried so far.
I get this error:
fileHandling.java:11: readArray(java.util.ArrayList<java.lang.String>) in fileHandling cannot be applied to ()
readArray();
^
1 error
My code:
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class fileHandling {
private ArrayList<String> Person;
public static void main(String[] args)throws Exception {
readArray();
}
private ArrayList readFile() throws Exception {
File file = new File("person.rtf");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
String str = scanner.nextLine();
Person.add(str);
}
return Person;
}
public void readArray(ArrayList<String> Person) {
for(int i =0; i < Person.size(); i++) {
System.out.println(Person.get(i));
}
}
}
I think the error is when I called my method, what is going inside the brackets?
You have a few issues (that I see).
1) You aren't instantiating an instance of your class.
2) You aren't reading the file.
3) You aren't calling readArray with the List.
4) You have no List instance.
5) ArrayList<String> readFile()
I think you want something like this,
private ArrayList<String> Person = new ArrayList<String>();
public static void main(String[] args) throws Exception
{
// readArray();
fileHandling fh = new fileHandling();
fh.readArray(fh.readFile()); // <-- something like this
}
You should use a bufferedInputStream to read your file...
variables should not be capitalized and your array should also be called persons and not Person.
Don't forget to initialize your
ArrayList persons = new ArrayList();
Your main method should call the read method first.
If you use Java 7, it is as easy as:
// returns a List<String> with all lines in the file
Files.readAllLines(thePath, StandardCharsets.UTF_8);
First you won't be able to access readArray() from your main since readArray() is not static. In your current context you'd need to create an instance of fileHandling in your main and call readArray() on it.
Second, your readArray() method is declared with an ArrayList Person as a parameter, but you're calling it without the parameter in your main method.
Third, it won't help with the compilation, but rule of thumb in Java is to capitalize the first letter of a class (Should be FileHandling) and to not capitalize the first letter of a declaration (ArrayList Person should really be ArrayList person).