標籤:
問題實現
實現一個閏年測試的JAVA代碼如下:
package leapyear;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;public class leapyear extends JFrame implements ActionListener{ private JTextField textField=null; private JButton btn; public leapyear(){ JFrame f = new JFrame("閏年"); JPanel p = new JPanel(); textField = new JTextField("",10); JButton btn = new JButton("確定"); JLabel label1 = new JLabel("輸入"); btn.addActionListener(this); p.add(label1); p.add(textField); p.add(btn); f.add(p); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(300, 200); f.setBounds(150,150,150,150); f.pack(); } public void actionPerformed (ActionEvent e){ String f; f =textField.getText(); String q=""; try{ int p1 = Integer.parseInt(f); if(checkleap(p1)){ q="該年份是閏年!"; } else{ q="該年份不是閏年!"; } } catch (NumberFormatException s) { q="非法輸入!"; } textField.setText(q); } public Boolean checkleap(int year) { Boolean temp = false; if (year % 4 == 0) { temp = true; } if (year % 100 == 0) { temp = false; } if (year % 400 == 0) { temp = true; } return temp; } public static void main(String[] args) { new leapyear(); } }
代碼的演算法簡單易懂,在限制非法操作中,我利用了try,catch的方法判斷輸入的是否為數字,如果不是數字則得到一條錯誤資訊。
測試案例
| 測試案例 |
預期輸出 |
實際輸出 |
| 1234 |
該年份不是閏年! |
該年份不是閏年! |
| 2000 |
該年份是閏年! |
該年份是閏年! |
| 1000 |
該年份不是閏年! |
該年份不是閏年! |
| abcd |
非法輸入! |
非法輸入! |
| #¥& |
非法輸入! |
非法輸入! |
測試
JAVA閏年測試與解決非法輸入