如何在对象中使用Arraylist作为另一个类

时间:2015-12-22 23:17:47

标签: java object arraylist javafx controller

我的程序应该从用户那里获取单词和定义,并将它们显示为闪存卡。我已经把所有的单词整理成了类等等,现在我需要做的就是这样,当我的应用程序按下一个按钮时,控制器类将执行一个方法,该方法将通过arraylist卡类并显示单词并最终显示定义。

我的问题是我有一个读者类的对象,其中包含所有卡片,我希望能够在getWordClick方法中调用随机卡片。我不知道如何在另一个班级中使用该对象。

public class Main extends Application{


@Override
public void start(Stage primaryStage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Scene.fxml"));
    primaryStage.setTitle("FlashCards");

    Scene scene = new Scene(root, 600, 400, Color.GREY);
    primaryStage.setScene(scene);
    primaryStage.show();
}


public static void main (String[] args){

    Reader r = new Reader();

    //Initialises the Arraylist and reads the file adding them to arraylist
    ArrayList<String> wordList = r.getWordList();
    r.OpenFile();
    r.readFile(wordList);
    r.closeFile();

    //Initialises the Definitions Arraylist and reads the file adding them
    ArrayList<String> definitionList = r.getDefinitionsList();
    r.OpenFile();
    r.readFile(definitionList);
    r.closeFile();

    /* IGNORE IS FOR TESTING PURPOSES
    //Wordlist is printed
    for (String i : wordList){
        System.out.println(i);
    }

    //Definitions list is printed
    for (String i : definitionList){
        System.out.println(i);
    } */

    //Card for each word and def is made
    ArrayList<Card> c = r.getCardList();
    Main m = new Main();
    r.cardSetter(m.addTerms(c, wordList.size(), wordList, definitionList));


    //Loops through and displays the word and defs
    for (Card i : c){
        System.out.printf("%s : %s\n",i.dispWord(),i.dispDef());
    }

    //Displays the window
    launch(args);
}

public ArrayList<Card> addTerms(ArrayList<Card> c, int q, ArrayList<String> word, ArrayList<String> def){
    for (int i = 0; i<q; i++){
        c.add(new Card(word,def,i));
    }
    return c;
}

}

这是读者类

public class Reader {

private Scanner x;
private Scanner sc;

//ArrayList to store the words
private ArrayList<String> wordList = new ArrayList<>();
//ArrayList to store the definitions
private ArrayList<String> definitionsList = new ArrayList<>();
//ArrayList to store the cards
private ArrayList<Card> cardList = new ArrayList<>();


//Simple scanner collects user input
public String getFileName(){
    sc = new Scanner(System.in);
    return sc.nextLine();
}

//Method to open the file and throw an exception if failed
public void OpenFile(){
    try{
        x = new Scanner(new File(getFileName()));
    }
    catch (Exception e){
        System.out.println("could not find file");
    }
}

//Assigns each line to a Array
public void readFile(ArrayList<String> e){
    while(x.hasNext()){
        e.add(x.nextLine());
    }
}

//Closes file
public void closeFile(){
    x.close();
}

//Returns the wordlist
public ArrayList<String> getWordList(){
    return wordList;
}

//Returns Definitionlist
public ArrayList<String> getDefinitionsList(){
    return definitionsList;
}

//Returns cardList
public ArrayList<Card> getCardList(){
    return cardList;
}

public void cardSetter(ArrayList<Card> c){
    c = cardList;
}
}

这是卡片类

public class Card {

private String word;
private String definition;

public Card(ArrayList<String> Word,ArrayList<String> Definition, int i){
    word = Word.get(i);
    definition = Definition.get(i);
}

public String dispWord(){
    return word;
}

public String dispDef(){
    return definition;
}

}

最后这是控制器

public class Controller {

Random rand = new Random();
private int Random;
//Makes the rand instance variable int so that the def class can use it

public Button wordBox;
public Label defBox;

public void getWordClick(){

}

public void goExit(){

}

public void goRand(){

}

public void getDefClick(){


}

public void goNext(){

}

public void goPrev(){

}

}

很抱歉我知道它很长但是代码只是供参考,我主要关心的是如何从ArrayList<Card>获取Reader r以便我可以在getWordClick()中使用它{1}}方法。从字面上看,任何帮助都是值得赞赏的,我只是需要有人在我被卡住的时候把我拉向正确的方向。

更新:我现在编辑了控制器类,看起来像这样     公共类控制器{

Random rand = new Random();
private int Random;
//Makes the rand instance variable int so that the def class can use it

public Button wordBox;
public Label defBox;


private Reader mReader = null;

public Controller(Reader reader){
    this.mReader = reader;
}

public Reader getReader(){
    return this.mReader;
}

public void getWordClick(){
    getReader();
}

public void goExit(){

}

public void goRand(){

}

public void getDefClick(){


}

public void goNext(){

}

public void goPrev(){

}

}

但现在关注的是当fxml文件运行并查找控制器时它将如何创建一个对象本身,还是会使用我创建的对象,因为我创建了一个对象,我将读者添加为构造函数。但是我不知道fxml文件将如何将它用于事件处理。

2 个答案:

答案 0 :(得分:0)

我看到一个简单的方法虽然我不知道它的内存效率如何:

在控制器类中声明

private Reader mReader = null;

添加构造函数

public Controller(Reader reader)
{
     this.mReader = reader;
}
public Reader getReader()
{
     return this.mReader;
}

因此,您对Controller类的声明的不同之处在于您将reader对象的引用传递给该类的引用。这是一个称为封装的概念。

编辑:

可以提供构造函数的类是强大的工具。多态性等是很好的研究课题,在开发方面有很多实际应用。我还打算推荐一些链接来检查,但我需要自己做更多的研究:p

快速谷歌的多态性java将给你足够的知识!

EDIT2 CODE REPRISE:

阅读器

public class Reader {

private Scanner x;
private Scanner sc;

//ArrayList to store the words
private ArrayList<String> readContent = new ArrayList<>();
private String filename = "";

public Reader()
{
    //if every time I want a new reader, I want to read user input
    //this.filename = readUserInput();
    //If I want to read indefinitely which I will do for now
    readIndefinitely();
}

//This will continuously read until the user enters a valid file name
public void readIndefinitely()
{
    while (!OpenFile())
    {
        filename = readUserInput();
    }
}
public Reader(String fileIWantToRead)
{
    this.filename = fileIWantToRead;
}

public String readUserInput()
{
    if (sc != null)
    {
       sc.close();
       sc = null;
    }
    sc = new Scanner(System.in);
    return sc.nextLine();
}
//Simple scanner collects user input
public String getFileName(){
    return filename;
}

//Method to open the file and throw an exception if failed
public boolean OpenFile(){
    try{
        //assume we already know the filename
        x = new Scanner(new File(filename));
    }
    catch (Exception e){
        System.out.println("could not find file");
        return false;
    }
    return true;
}

//Assigns each line to a Array
public ArrayList<String> readFile(){
OpenFile();
try
{
    readContent.clear();
    while(x.hasNext()){
        readContent.add(x.nextLine());
    }
}
catch(Exception e)
{
    e.printStackTrace();
}
closeFile();
return readContent;
}

//Closes file
public void closeFile(){
    x.close();
}
public String getReadContent()
{
   return readContent;
}
public void clearReadContent()
{
   readContent.clear();
}
} //end class

卡类

public class Card {
    private String word;
    private String definition;

    public Card(String word, String definition){
        this.word = word;
        this.definition = definition
    }

    public String getWord(){
        return word;
    }

    public String getDefinition(){
    return definition;
    }

}

主类

public class Main extends Application{

    private ArrayList<Card> mCards = new ArrayList<>();
    public Main(ArrayList<Card> cards)
    {
        this.mCards = cards;
        //do what is required to get the cards to the controller either here or start
    }

    @Override
public void start(Stage primaryStage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Scene.fxml"));
    primaryStage.setTitle("FlashCards");

    Scene scene = new Scene(root, 600, 400, Color.GREY);
    primaryStage.setScene(scene);
    primaryStage.show();
}

    public static void main (String[] args){

        Reader wordReader = new Reader();
        Reader definitionReader = new Reader();
        wordReader.readFile();
        definitionReader.readFile();

        /* IGNORE IS FOR TESTING PURPOSES
        //Wordlist is printed
        for (String i : wordList){
            System.out.println(i);
        }

        //Definitions list is printed
        for (String i : definitionList){
            System.out.println(i);
        } */

        //if we know that both the words and definitions are the same size, we can make cards
        ArrayList<Card> c = makeCards(wordReader.getReadContent(), definitionReader.getReadContent());
    //Loops through and displays the word and defs
        for (Card i : c){
            System.out.printf("%s : %s\n",i.dispWord(),i.dispDef());
        }

        Main m = new Main(c);
    //Displays the window
        //Not sure how FXMLLoader and this functions as I don't work too much with java but if you pass a reference to main in you'd be good to go
        launch(args);
    }

public ArrayList<Card> makeCards(ArrayList<String> word, ArrayList<String> def){
    ArrayList<Card> cards = new ArrayList<>();
    for (int i = 0; i<word.size(); i++){
        c.add(new Card(word.get(i),def.get(i)));
    }
    return c;
}
}

控制器:

public class Controller {
    Random rand = new Random();
    private int Random;
    //Makes the rand instance variable int so that the def class can use it
    private int position = 0;
    public Button wordBox;
    public Label defBox;
    //instead of passing in an entire reader we just pass in cards (oops!)
    private ArrayList<Card> mCards = new ArrayList<>();

    public Controller(ArrayList<Card> cards){
        this.mCards = cards;
    }

    public ArrayList<Card> getCards()
    {
        return this.mCards;
    }

    public void goExit(){
        //Exit program
    }

    public void goRand(){
        //nextInt in range is ((max - min) + 1) + min and we want a position that corresponds from 0 to the size of cards

        position = rand.nextInt(cards.size());
        wordBox.setText(cards.get(position).getWord());
        defBox.setText(cards.get(position).getDefinition());
    }

    public void getDefClick(){
        //Call to either cards.get(position).getDefinition() or defBox.getText().toString()

    }

    public void goNext(){
        //because retrieving from cards starts at index 0 the equivalent position will require a +1 and we are looking for the next
        if (cards.size() < position+2)
        {
            position++;
            wordBox.setText(cards.get(position).getWord();
            defBox.setText(cards.get(position).getDefinition();
        }
    }

    public void goPrev(){
        //same concept as above but assume that position is already an acceptable value
        if (position != 0 && !cards.isEmpty())
        {
            position--;
            wordBox.setText(cards.get(position).getWord());
            defBox.setText(cards.get(position).getDefinition());
        }
    }
}

答案 1 :(得分:-1)

在我看来,您只需要更多练习面向对象设计概念。

让我们从逻辑上看这个问题。您有一个Controller类,用于控制Card列表的视图。这里显而易见的问题是,您的Controller实际上缺少要控制的Card列表,因此,您应该将其添加到类中。

public class Controller {
    // The list of Cards that are being controlled.
    private ArrayList<Card> cards;

    ...
}

现在,这只是增加了Controller的抽象概念。显然,我们需要一种方法来指定Card应该使用的Controller列表。因此,我们应该创建一个构造函数。

public class Controller {
    // The list of Cards that are being controlled.
    private ArrayList<Card> cards;

    ...

    // A list of cards must be specified when creating a Controller instance.
    public Controller(ArrayList<Card> cards) {
        this.cards = cards;
    }

    ...
}

或者,您可以使用mutator方法(a.k.a set ter方法)使用称为封装的概念设置卡片列表,如KoalaKoalified所述。

public class Controller {
    // The list of Cards that are being controlled.
    private ArrayList<Card> cards;

    ...

    // Specify a list of cards.
    public void setCards(ArrayList<Card> cards) {
        this.cards = cards;
    }

    ...
}

现在,在Main内部,或者在创建Controller实例的任何地方,您都可以这样做:

Controller controller = new Controller(r.getCardList());

或者,如果您更喜欢使用mutator方法,那么:

Controller controller = new Controller();
controller.setCards(r.getCardList());

现在,您的Controller类可以在其每个方法中引用Card列表,如果您有其他来源提供Cards列表,则可能会重复使用它第

我强烈建议对面向对象设计(OOD)进行更多研究。 Java非常依赖于这种类型的设计。你似乎在你的程序中散布着一些零碎的东西,但你似乎对一些细节和可能的大局略有混淆。