I right now made an arraylist and returned it just like in a void Right now I got something like this I know I have to change the static void t something else to return it but I lost that version of the code.
package Spel;
import java.util.ArrayList;
import java.awt.event.KeyEvent;
import Tools.*;
import java.awt.Color;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
Public Class Surrounding{
public String a;
public static void main(String[] args) { // this just selects different specific words to put into an arraylist
File f = new File("words.txt");
try (FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
List<String> list = new ArrayList<>();
String line = br.readLine();
while (line != null) {
if (line.length() == 4) {
list.add(line);
}
line = br.readLine();
}
System.out.println(list);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
public void otherstuff(){
list.get(6)
// here I want to do some stuff with some values out of the arraylist
}
}
What do I do to use the filled list from the one void to the other? The problem is not the ArrayList filling or any mistakes I make in the declaring of the ArrayList just how to use the returned list
CodePudding user response:
You can either define your list as static member or non-static member & access it within different class methods something like:
public class Test {
static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
list.add("aa");
list.add("bb");
list.add("cc");
list.add("dd");
new Test().doOtherStuff();
}
public void doOtherStuff() {
System.out.println(list);
}
}
So same way, remove your list declaration from main
& put it outside main, & then access list from main
as well as from doOtherStufff()
in static way.