Catch块串/号验证
在catch块我想打印输入有效的卡没有,如果有人进入 字符串或数字小于13或大于16Catch块串/号验证
我刚才说NumberFormatException的,但它什么都不做如果我输入一个字符串或数字小于13或大于16的数字。
如何在这里有例外?此代码仅用于验证信用卡。我只是需要试试catch块的帮助。
import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
//CreditCard class
public class CreditCard {
//Variable declaration
private JFrame frame;
private JPanel panel;
private JTextField textField;
private JLabel label;
private JLabel resLabel;
private JButton validateBtn;
//Constructor
public CreditCard() {
frame = new JFrame("Credit Card Details");
frame.setSize(350, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create a new panel and add the frame to the panel.
panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
// add label
label = new JLabel("Enter Credit Card No.");
label.setBounds(10, 20, 165, 25);
panel.add(label);
// add input text
textField = new JTextField(16);
textField.setBounds(10, 50, 165, 25);
panel.add(textField);
// create a validation button
validateBtn = new JButton("Validate");
validateBtn.setBounds(10, 80, 80, 25);
panel.add(validateBtn);
frame.setVisible(true);
// set label as valid or invalid
resLabel = new JLabel();
resLabel.setBounds(180, 50, 265, 25);
panel.add(resLabel);
// add event listener
validateBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String text = textField.getText();
if (text.length() < 13 || text.length() > 16) {
resLabel.setText("Entered Value Must Be Between 13-16 Chars");
return;
}
boolean isValid = validateText(text);
if(isValid)
resLabel.setText("Credit Card is Valid");
else
resLabel.setText("Credit Card is Invalid");
}catch(NumberFormatException f){
System.out.println("Enter Valid Card Number");
}
}
private boolean validateText(String text) {
int rSum = 0, lSum = 0;
for (int i = text.length() - 2; i >= 0; i -= 2) {
if (!Character.isDigit(text.charAt(i)))
return false;
int currentNum = Character.getNumericValue(text.charAt(i));
currentNum *= 2;
if (currentNum > 9) {
int tempSum = 0;
while (currentNum >= 10) {
tempSum += currentNum % 10;
currentNum /= 10;
}
tempSum += currentNum;
currentNum = tempSum;
}
rSum += currentNum;
}
System.out.println(rSum);
for (int i = text.length() - 1; i >= 0; i -= 2) {
if (!Character.isDigit(text.charAt(i)))
return false;
int currentNum = Character.getNumericValue(text.charAt(i));
lSum += currentNum;
}
System.out.println(lSum);
int totalSum = lSum + rSum;
if (totalSum % 10 == 0)
return true;
return false;
}
});
}
}
回答:
如果要引发异常,则必须将其包含在代码中。你可以在你希望发生的地方添加“throw new NumberFormatException()
”来达到目的。
无论如何,在所描述的情况下抛出异常并不是最好的办法,因为抛出异常会阻止程序运行“正常”的方式。我建议使用“if
”语句来检查一个输入 - 如果输入满足你,你继续,但如果不是的话 - 你提供下一个输入(用一个无限的while循环围绕前面提到的“if
”声明,正确的输入完成)或者简单地写入错误消息。
以上是 Catch块串/号验证 的全部内容, 来源链接: utcz.com/qa/258488.html