-2

I know this may be a really stupid question because my professor says I'm very close but I've tried so many different things. I've made an alarm clock and all that is left is to get the alarm option to compare to the time and if they are the same, print "Alarm" so I know it works. I've tried:

 if(time.equals(alarmHour))
        System.out.println("Alarm");

with

String time = hour + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10;

and

String alarmHour;

if(sixAlarm.isSelected())
            alarmHour = "06:00:00";

etc. I have printed the time variable so I know it is hh:mm:ss format, which matches the alarmHour string precisely.

But I also tried using a function

 public void alarm(String time, String alarmHour){
    if(time.equals(alarmHour))  {
        System.out.println("Alarm");
    }
 }

while calling it under the main class

public DigitalClock() {
// ...
alarm(time, alarmHour);
}

but it still won't work. I've tried both comparisons for Strings (time == alarmHour) and (time.equals(alarmHour)). Neither work. Someone please help. I'm close to just turning it in as it is because I have no idea why it's not working.

UPDATE --- Complete program:

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;
import java.awt.Color;
import java.util.GregorianCalendar;

public class DigitalClock extends JFrame implements ActionListener {
JLabel timeLabel = new JLabel();
JPanel alarmGroup = new JPanel();
JButton soundButton = new JButton();
JLabel alarmLabel = new JLabel();
SimpleDateFormat sdf = new SimpleDateFormat("KK:mm:ss a");
Timer timer;
private JCheckBox sixAlarm = new JCheckBox("6:00 AM");
private JCheckBox eightAlarm = new JCheckBox("8:00 AM");
private JCheckBox tenAlarm = new JCheckBox("10:00 AM");
private JCheckBox twelveAlarm = new JCheckBox("12:00 AM");
private AudioClip audioClip;
private String alarmHour;

// calendar values
Calendar calendar = new GregorianCalendar();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String time = hour + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10;

public DigitalClock() {
    super();

    // get current time from system and display
    timeLabel.setText(sdf.format(new Date(System.currentTimeMillis())));

    // set text and specifications for alarmGroup label
    alarmGroup.setPreferredSize(new Dimension(100, 50));
    alarmGroup.setLayout(new GridLayout(5, 1));
    alarmGroup.add(alarmLabel);
    alarmLabel.setForeground(Color.BLUE);
    alarmLabel.setText("Alarm Group");
    alarmGroup.add(sixAlarm);
    alarmGroup.add(eightAlarm);
    alarmGroup.add(tenAlarm);
    alarmGroup.add(twelveAlarm);
    alarmGroup.setLocation(50, 50);

    // set specifications for button
    alarmGroup.add(soundButton);
    soundButton.setText("Test Alarm");
    soundButton.setForeground(Color.BLUE);
    soundButton.setBackground(Color.LIGHT_GRAY);

    // set font specifications for time
    timeLabel.setFont(new Font("Dialog", Font.BOLD, 80));
    timeLabel.setForeground(Color.GREEN);

    // set timer to update clock ever 0.5 seconds
    timer = new Timer(500, this);
    timer.setRepeats(true);
    timer.start();

    // handler class with listeners for checkboxes
     HandlerClass handler = new HandlerClass();
     sixAlarm.addItemListener(handler);
     eightAlarm.addItemListener(handler);
     tenAlarm.addItemListener(handler);
     twelveAlarm.addItemListener(handler);
     buttonClickClass click1 = new buttonClickClass();
     soundButton.addActionListener(click1);

    // add label and alarmGroup to DigitalClock and set visibility
    this.add(timeLabel, BorderLayout.NORTH);
    this.add(soundButton, BorderLayout.EAST);
    this.add(alarmGroup);
    this.pack();
    this.setVisible(true);

    alarm(time, alarmHour);
}

public void alarm(String time, String alarmHour){
    if(time.equals(alarmHour))  {
        System.out.println("Alarm");
    }
}

private class HandlerClass implements ItemListener {
    public void itemStateChanged(ItemEvent event){
        if(sixAlarm.isSelected())  
            alarmHour = "06:00:00";
        if(eightAlarm.isSelected())
            alarmHour = "08:00:00";
        if(tenAlarm.isSelected())
            alarmHour = "10:00:00";
        if(twelveAlarm.isSelected())
            alarmHour = "15:31:45";
    }
}

class buttonClickClass implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e){
        if(e.getSource() == soundButton)
        audioClip.play();
    }
}

public class audioClip extends JApplet {
    public void init(){
     URL urlForAudio = getClass().getResource("audio/denmark.midi");
     audioClip = Applet.newAudioClip(urlForAudio);
     audioClip.loop();
 }

@Override
 public void start(){
     if(audioClip != null)
         audioClip.play();
 }

@Override
 public void stop(){
     if(audioClip != null)
         audioClip.stop();
 }
 }

public void actionPerformed(ActionEvent e) {
    // if timer starts then set new time
    if (e.getSource().equals(timer)) {
        // set new time
        timeLabel.setText(sdf.format(new Date(System.currentTimeMillis())));
    }
}

// main method
public static void main(String[] args) {
    // create frame
    JFrame clockFrame = new DigitalClock();
    clockFrame.setTitle("Java Final - Digital Alarm Clock");
    clockFrame.setSize(485, 300);
    clockFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    clockFrame.setLocationRelativeTo(null);
    clockFrame.setVisible(true);
    clockFrame.getContentPane().setBackground(Color.BLACK);
    clockFrame.setResizable(false);
}
}

4 Answers4

2

Likely because your hour/minute/second value is < 10 producing something like 12:3:15 instead of 12:03:15. You should only be using .equals() to compare the strings. You will probably need to update your formatting to left pad your value with 0 if it is < 10.

Using your code from above you aren't padding the hours and your string is "06:00:00"

    int hour = 6;
    int minute = 3;
    int second = 15;
    String time = hour + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10;
    System.out.println(time);

Produces: "6:03:15" which will not be equal because of the hours value. Update your code to apply the same formatting you did for the minutes and seconds to the hour.

Like this:

String time = "" + hour / 10 + hour % 10 + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10;

Notice you must force string concatenation by leading the expression with "" +. That wasn't necessary for the minutes and seconds because it was already doing string concatenation beyond the first + ":".

Sorry I didn't see your updated code in time but the reason it wasn't working is that you were only calling the alarm method once from the constructor. This method should have been invoked every time the clock updated in the ActionPerformed method

public void actionPerformed(ActionEvent e) {
    // if timer starts then set new time
    if (e.getSource().equals(timer)) {
        // set new time
        String currentTime = sdf.format(new Date(System.currentTimeMillis()));
        timeLabel.setText(currentTime);
        alarm(currentTime, alarmHour);  // Check if alarm should trigger
    }
}

In addition to that your SimpleDateFormatter was setup with "KK:mm:ss a" which means your time string was appending AM|PM. Your alarm values were not appending AM|PM in your HandlerClass. The values should have been similar to alarmHour = "10:00:00 PM"; so the comparison to the simple date formatted string would be .equal().

Jeff Ward
  • 1,109
  • 6
  • 17
  • I did try the .equals() but that did nothing. I checked and they do print in the 12:03:15 format rather than 12:3:15 format. – FlummoxedUser Apr 26 '14 at 20:50
  • @FlummoxedUser I updated my answer I believe that should fix the issue you were having. – Jeff Ward Apr 26 '14 at 21:00
  • Ok, I changed the String time declaration to: String time = hour + ":" + minute % 10 + ":" + second % 10; but it still isn't working. – FlummoxedUser Apr 26 '14 at 21:13
  • @FlummoxedUser Updated again. You need to force string concatenation otherwise the hours would still be formatted improperly. – Jeff Ward Apr 26 '14 at 21:45
  • Well, I tried that and that didn't work either. I'm giving up on this. I'm obviously not experienced enough to be doing this project in my class. I'll turn it in as is and accept whatever grade I get for it being incomplete. Thank you for your responses, you were the most helpful. Everyone else seems to think I intentionally misled them, I just have a lot of difficulty when it comes to Java. – FlummoxedUser Apr 26 '14 at 22:23
  • @FlummoxedUser Sorry I didn't see your updated code in time. I updated my answer to address the issues you were having. Hope it helps. – Jeff Ward Apr 27 '14 at 02:26
0

try to add it to the Date class and compare them..

    DateFormat format = new SimpleDateFormat( "kk:mm:ss");
    String alarm = "06:00:00";
    Date alarm2 = format.parse(alarm);
    String time = "06:00:00";
    Date time2 = format.parse(time);
    if(alarm2.getTime() == time2.getTime())
        System.out.println("I am the same");
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
0

This should give you an idea. Try using the correct objects.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;


public class TimeFormattingExample {

static final SimpleDateFormat sd = new SimpleDateFormat("hh:mm.ss");

public static void main(String[] args) {
    Calendar time = getCalendarForTime(6, 0, 0);
    Calendar alarm = getCalendarForTime(6, 0, 0);

    String formattedTime = sd.format(time.getTime());
    String formattedAlarm = sd.format(alarm.getTime());

    System.out.println("Time: " + formattedTime + " (" + time.getTimeInMillis() + "ms)");
    System.out.println("Alam: " + formattedAlarm + " (" + alarm.getTimeInMillis() + "ms)");

    System.out.println("calendars (time and alarm) are equal? -> " + time.equals(alarm));
    System.out.println("formatted time and alarm are equal -> " + formattedTime.equals(formattedAlarm));
}

public static Calendar getCalendarForTime(int hours, int minutes, int seconds) {
    Calendar calendar = new GregorianCalendar(0,0,0);
    calendar.set(Calendar.HOUR, hours);
    calendar.set(Calendar.MINUTE, minutes);
    calendar.set(Calendar.SECOND, seconds);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar;
}

}
Alex_M
  • 1,824
  • 1
  • 14
  • 26
0

There is no way this can work, and contrary to what you told me in comments, the two values are not the same at all. Indeed, time is initialized to the current time, in the format H:mm:ss:

String time = hour + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10;

so, for example, 3:12:47.

alarmHour is not initialized at all, so its value is null:

private String alarmHour;

If you had printed these two values as I suggested, you would have made that obvious. You told me you did, but you didn't:

public void alarm(String time, String alarmHour){
    System.out.println("time = " + time);
    System.out.println("alarmHour = " + alarmHour);

    if (time.equals(alarmHour)) {
        System.out.println("Alarm");
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255