Java比较两个字符串和打印行

时间:2014-04-26 20:40:57

标签: java string clock alarm

我知道这可能是一个非常愚蠢的问题,因为我的教授说我非常接近,但我尝试了很多不同的事情。我已经制作了一个闹钟,剩下的就是让警报选项与时间进行比较,如果它们是相同的,打印“警报”,这样我知道它有效。我试过了:

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

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

String alarmHour;

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

等。我打印了时间变量,所以我知道它是hh:mm:ss格式,它与alarmHour字符串精确匹配。

但我也尝试过使用函数

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

在主要类

下调用它
public DigitalClock() {
// ...
alarm(time, alarmHour);
}

但它仍然无效。我已经尝试过比较Strings(time == alarmHour)和(time.equals(alarmHour))。都没有工作。有人请帮忙。我接近只是将其打开,因为我不知道它为什么不起作用。

更新---完成程序:

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 个答案:

答案 0 :(得分:2)

可能因为你的小时/分钟/秒值是< 10产生类似12:3:15而不是12:03:15的东西。您应该只使用.equals()来比较字符串。您可能需要更新格式,以便使用0来填充您的值,如果它是< 10。

使用上面的代码,你不会填补小时数,而你的字符串是" 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);

生成:"6:03:15"由于小时值而不相等。更新代码以应用与分钟和秒到小时相同的格式。

像这样:

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

请注意,您必须通过使用"" +引导表达式来强制进行字符串连接。这对于分钟和秒来说并不是必需的,因为它已经在第一个+ ":"之外进行了字符串连接。

抱歉,我没有及时看到您更新的代码,但原因是您只是从构造函数中调用alarm方法一次。每次在ActionPerformed方法

中更新时钟时,都应该调用此方法
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
    }
}

除此之外,您的SimpleDateFormatter设置为"KK:mm:ss a",这意味着您的时间字符串附加了AM | PM。您的警报值未在HandlerClass中附加AM | PM。这些值应与alarmHour = "10:00:00 PM";类似,因此与简单日期格式化字符串的比较将为.equal()

答案 1 :(得分:0)

尝试将其添加到Date类并进行比较..

    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");

答案 2 :(得分:0)

这应该会给你一个想法。尝试使用正确的对象。

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;
}

}

答案 3 :(得分:0)

这没有办法可行,而且与你在评论中告诉我的相反,这两个值根本不相同。实际上,时间初始化为当前时间,格式为H:mm:ss:

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

所以,例如,3:12:47

alarmHour根本没有初始化,所以它的值为null:

private String alarmHour;

如果您按照我的建议打印了这两个值,那么您就会明白这一点。你告诉我你做了,但你没有:

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");
    }
}