题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续 判断第二个字母。
运行结果:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class JudgeWeekend extends JFrame{
static String[] week = {"Sunday(日)","Monday(一)","Tuesday(二)"
,"Wednesday(三)","Thursday(四)","Friday(五)","Saturday(六)"};
public static void main(String[] args) {
new JudgeWeekend();
System.out.println(whatDay2("t"));
}
public JudgeWeekend() {
setLayout(new BorderLayout());
JLabel label1 = new JLabel("输入星期:");
JTextField input = new JTextField(20);
JPanel inPanel = new JPanel(new BorderLayout());
inPanel.add(label1, BorderLayout.NORTH);
inPanel.add(input, BorderLayout.CENTER);
JLabel label2 = new JLabel("查询结果:");
JTextArea res = new JTextArea(3, 20);
res.setEditable(false);
JPanel outPanel = new JPanel(new BorderLayout());
outPanel.add(label2, BorderLayout.NORTH);
outPanel.add(res, BorderLayout.CENTER);
input.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
JTextField textField = (JTextField) e.getSource();
String in = textField.getText();
//输入超过2个字符就不在判断
if (in != null && in.length() > 0) {
res.setText(whatDay2(in));
}
}
});
add(inPanel, BorderLayout.NORTH);
add(outPanel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
//根据输入字符串判断
static String whatDay(String in) {
StringBuilder res = new StringBuilder();
String inLow = in.toLowerCase();
for (int i=0; i<7; i++) {
//使用每个字符串的前2个子串判断,但有个限制,对输入字符的长度要小于2
if (week[i].toLowerCase().substring(0, 2).contains(inLow)) {
res.append(week[i]+"\n");
}
}
return res.toString();
}
//方法2
static String whatDay2(String in) {
StringBuilder res = new StringBuilder();
int len = in.length();
String inLow = in.toLowerCase();
for (int i=0; i<7; i++) {
int index = 0;
while (index < len) {
if (week[i].toLowerCase().charAt(index)
!= inLow.charAt(index)) {
break;
} else {
index++;
}
}
System.out.println("index"+index);
if (index == len) {
res.append(week[i] + "\n");
}
}
return res.toString();
}
//根据第一个字母判断星期几
static String whatDay(char ch) {
StringBuilder res = new StringBuilder();
//转换为小写
char chLow = charToLowCase(ch);
for (int i=0; i<7; i++) {
if (chLow == charToLowCase(week[i].charAt(0))) {
res.append(week[i]+"\n");
}
}
return res.toString();
}
//将字符转换为小写
static char charToLowCase(char ch) {
return ((ch+"").toLowerCase()).charAt(0);
}
}