在构造函数中将self添加到静态列表中

时间:2014-03-24 04:42:35

标签: java

我基本上想要将对象的实例(在它自己的构造函数中)添加到列表中。我已经尝试了这个关键字,但仍然没有。

你会在中间发现问题。它是“alarms.add(this); // TODO:这就是问题。”

提前致谢!以下是相关代码。

package com.brandonmxb.bpi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.sun.media.sound.JavaSoundAudioClip;

public class Alarm extends Thread {
    private String tAlarm = null;
    private boolean enabled = true; // thread for alarm running
    private boolean alarm = false; // thread for alarm going off
    private String desc = "";

    private SimpleDateFormat ft = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    private static SimpleDateFormat nt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    private static List<Alarm> alarms = new ArrayList<Alarm>(); // global list of all alarms, only one
    private static Settings saved; // alarm Settings file

    public void run(){ // always running, separate thread
        //System.out.println("Running Alarm thread...");
        String nTime = null;
        String nAlarm = null;

        while(enabled){ // always run and wait
            //nTime = df2.parse().toString();
            try {
                nAlarm = this.tAlarm.replace("XX", String.valueOf(Clock.getDateDay())); // replace with current day of month
                String s = Clock.getTime().toString();

                nTime = nt.format(ft.parse(s));

                //System.out.println(nTime + "=" + nAlarm); //debug

                if(nTime.equals(nAlarm)) // is it alarm time?
                    sound();
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //Log.makeLog(0, "Alarm completely disabled!");
    }

    public Alarm(String date, String desc, boolean save){ // set up alarm
        this.tAlarm = date; // set local alarm time
        this.desc = desc; // set description for obj alarm

        alarms.add(this); // TODO: This is the problem.

        if(save){
            saved.add(this.tAlarm, this.desc); // adds alarm to file
            saved.save();
        }
        this.start(); // start alarm clock threading
    }

    public Alarm(){ // called once upon init to LOAD alarms
        // load alarms from settings
        saved = new Settings("alarms.txt"); // makes new Setting class, 
        alarms.clear(); // should be empty, but clears anyway

        for(int i = 0; i < saved.size(); i++){
            String date = saved.getOpt(i);
            System.out.println("Opt: " + date);
            String desc = saved.get(saved.getOpt(i));
            System.out.println("Val: " + desc);

            alarms.add(new Alarm(date, desc, false)); 
        }
        Log.makeLog(0, "Alarm clock system loaded and initialized.");
    }

    public static void remove(int index){
        alarms.remove(index); // removes from alarms list
        saved.removeOpt(index); // removes from save file
        saved.save(); // save to file
    }

    public void sound(){ // make loud sound and alert as alarm
        Log.makeLog(0, "Alarm at " + tAlarm + " is about to go off.");
        Speak.Speak("Alarm: " + this.desc);

        alarm = true; // alarm is going off!
        while(alarm){ // alarm sounding off!
            try {
                new JavaSoundAudioClip(new FileInputStream(new File("res/tone.wav"))).play();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Log.makeLog(0, "Alarm sound ended!");
    }

    public static List<Alarm> list(){ // return list of all added alarms
        return alarms;
    }

    public String getTime(){ // return alarm's time
        return tAlarm;
    }

    public String getDesc(){ // returns description of alarm
        return desc;
    }

    public boolean getAlarm(){ // returns if alarm is sounding
        return alarm;
    }

    public void setOff(){
        alarm = false; // disable current alarm sounding off
    }

    public void disable(){
        enabled = false;
        Log.makeLog(0, "Alarm '" + desc + "' disabled!");
    }
}

编辑: 感谢大家的投入!所有惊人的答案和想法,但我想我可能已经过度复杂化了。我想我会选择@ sayed.jalil的简单路线。

(Main class)
Alarm a = new Alarm(Date, Desc, true); // make new alarm with date and description
Alarm.add(a); // adds to static list

(Alarm class, where the prob was)
public Alarm(String date, String desc, boolean save){ // set up alarm
    this.tAlarm = date; // set local alarm time
    this.desc = desc; // set description for obj alarm
    ... nothing here really.

(Alarm class, new add to list function)
public static void add(Alarm a){
    alarms.add(a); // important part
}

4 个答案:

答案 0 :(得分:1)

这看起来像是一个设计问题。为什么您希望Alarm类中有警报列表?该类应该被认为代表一个单一警报。

您可以尝试创建另一个类,例如AlarmList(我不擅长名字),在那里,您可以存储Alarm个实例。

答案 1 :(得分:1)

代码压缩:

public Alarm(String date, String desc, boolean save){
    alarms.add(this);
}

public Alarm(){
    for(int i = 0; i < saved.size(); i++){
        // alarms.add !!
        //     v
        alarms.add(new Alarm(date, desc, false));
    }
}

您要将new Alarm添加到列表中两次。 new语句嵌套在add的调用中,并且它还会在其构造函数中第二次添加自身。如果这是您正在讨论的问题,您应该删除其中一个添加。

请注意,我还对使用no-arg构造函数对clear列表,读取设置,创建新实例等感到震惊。您不应该使用构造函数来执行此类操作静态初始化逻辑。相反,将初始化逻辑重构为static void方法或static { }初始化程序块。

答案 2 :(得分:0)

从构造函数中删除alarms.add行。定义一个新的静态函数,将一个报警对象作为参数传递给它。例如,你可以这样做:

    public void createAlarm(){
        Alarm al = new Alarm();
        Alarm.insertAlarm(al);
    }

    public static insertAlarm(Alarm al){
        alarms.add(al);
    }

这将为您完成,但您不应该在警报类中列出警报对象。

答案 3 :(得分:-1)

我不了解问题所在?你想要实现哪些失败? &#34;但仍然没有&#34;目前还不清楚。

如果我在您的类中添加main()方法,我会在静态列表中找到正确插入的Alarm实例:

public static void main(String[] args) {
  Alarm alarm = new Alarm("date", "desc", false);
  System.out.println("alarms.size(): " + alarms.size());
}

输出:&#34; alarms.size():1&#34;。

您还期待其他一些结果吗?