Reputation: 219
Here is my first method. I have a file that I added its contents to an ArrayList. I can print that just fine but I need to create a method that adds line numbers to the beginning of each String. I can do that outside the method but i'm having problems creating a method that returns an arrayList so i can use the updated arrayList in other methods and then I need to display the updated ArrayList. Here is my code.
My output for the first method should be 1 bird 2 cat etc...
My output for the second method should return the elements in the ArrayList in reverse order. 2 cat 1 bird etc...
import java.util.*;
import java.io.*;
public class List
{
public static void main(String[] args) throws IOException
{
int line =1;
ArrayList<String> textArray = new ArrayList<String>();
ArrayList<String> newArray = new ArrayList<String>();
File f = new File("src/List.txt");
Scanner sc = new Scanner(f);
int num = 1;
while(sc.hasNext())
{
textArray.add(sc.nextLine());
}
numbered(textArray);
reverseOrder(textArray);
}
public static ArrayList<String> numbered(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : results)
{
r = num + " " + results;
num++;
}
return results;
}
public static ArrayList<String> reverseOrder(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : results)
{
}
return results;
}
Upvotes: 0
Views: 103
Reputation: 1468
Have not tested this but it should work. As you can see pretty straight forward. Best of Luck and happy coding.
public ArrayList<String> numList(ArrayList<String> originalArrayList)
{
ArrayList<String> newNumberedList = new ArrayList<String>();
for(int i = 0;i< originalArrayList.size(); i++){
int newi = i+1;
newNumberedList.add(newi+". "+originalArrayList.get(i));
}
return newNumberedList ;
}
Upvotes: 1
Reputation: 330
You are returning your arrays correctly, the problem is that you are creating new Objects inside your methods, instead of using the ones you receive as parameters
ArrayList<String> results = new ArrayList<String>(textArray.size());
So you are iterating empty arrays. Inside your for loop, you could just iterate the received ArrayList
for (String r : textArray)
Also, your results array is always empty, you should add new elements like this:
results.add(r);
This may work:
public static ArrayList<String> numbered(ArrayList<String> textArray)
{
ArrayList<String> results = new ArrayList<String>(textArray.size());
String s;
int num = 1;
for (String r : textArray)
{
r = num + " " + results;
num++;
results.add(r);
}
return results;
}
Upvotes: 1
Reputation: 7082
You are instantiating the 'results' arraylist, and iterating it. You need to iterate the textArray list for starters and call results.add("text");
Upvotes: 0