JAVA閏年測試與解決非法輸入

來源:互聯網
上載者:User

標籤:

問題實現

實現一個閏年測試的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閏年測試與解決非法輸入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.