我一直在為我的計算機科學內部評估撰寫代碼,我即將完成它但一直發現這個錯誤,我不確定如何解決它。
這是我該部分的代碼:
JButton createbutton = new JButton("Create");
createbutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String[] characters = { "!", "#", "$", "%", "^", "&", "*" };
boolean passcontains = false;
for (int i = 0; i < characters.length; i ) {
if (new String(passwordfield.getPassword()).contains(new String(characters[i]))) {
passcontains = true;
}
}
boolean emcontains = false;
for (int i = 0; i < characters.length; i ) {
if (new String(emailfield.getText()).contains(new String(characters[i]))) {
emcontains = true;
}
}
loop: if (passwordfield.getPassword().length == 0
|| passwordfield.getPassword().length < 8
|| passcontains == false) {
message("INCORRECT PASSWORD\ncheck README");
} else {
if (emailfield.getText().length() == 0 || emcontains
|| emailfield.getText().contains("@") == false
|| emailfield.getText().contains(".") == false) {
message("INCORRECT EMAIL\ncheck README");
} else {
boolean pass = true;
for (int i = 0; i < database.size(); i ) {
if (database.get(i).getEmail() == emailfield.getText()) {
pass = false;
}
}
if (pass == true) {
database.add(
create(emailfield.getText(), new String(passwordfield.getPassword())));
write();
frame.setVisible(false);
message("SUCCESSFULLY MADE ACCOUNT");
frame.dispose();
} else {
message("AN ACCOUNT WITH THAT EMAIL ALREADY EXISTS\n GO TO LOGIN");
emailfield.setText("");
passwordfield.setText("");
break loop;
}
}
}
}
});
編輯:我自己解決了這個問題,我有一個函式去'create(input1,input2)'但是由于我以前版本的代碼檢查演算法包含在其中,因此它完成了兩次檢查并輸入了一個while 回圈。感謝您的回復)。
uj5u.com熱心網友回復:
不要那樣做!
遵循關注點分離和單一職責原則。
不要將這樣的邏輯放在負責向用戶展示內容的代碼中。使應用程式的業務邏輯遠離 GUI 代碼。創建一些類并將帶有邏輯的代碼放在那里。然后在您的 GUI 中,您將以簡單的方式呼叫此代碼,一切都會變得更好。這是一個學校專案的事實,并不意味著您提供“正常作業”的代碼。
檢查我的方法:
public class Account {
private final Email email;
private final Password password;
public Account(Email email, Password password) {
Objects.requireNonNull(email, "An account cannot have null email");
Objects.requireNonNull(email, "An account cannot have null password");
this.email = email;
this.password = password;
}
public Email getEmail() {
return email;
}
public Password getPassword() {
return password;
}
public static class InvalidAccountInformationException extends RuntimeException {
public InvalidAccountInformationException(String message) {
super(message);
}
}
}
.
public class Email {
private final String value;
private Email(String value) {
this.value = value;
}
public String value() {
return value;
}
// Eclipse generated
@Override
public int hashCode() {
return Objects.hash(value);
}
// Eclipse generated
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Email other = (Email) obj;
return Objects.equals(value, other.value);
}
public static Email of(final String email) {
if (email == null)
throw new InvalidAccountInformationException("Email cannot be empty.");
String trimmedEmail = email.trim();
if (trimmedEmail.isEmpty())
throw new InvalidAccountInformationException("Email cannot be empty.");
if (!isValidEmailAddress(trimmedEmail))
throw new InvalidAccountInformationException("Email is not a valid email address.");
return new Email(trimmedEmail);
}
/*
* Shamelessly copy-pasta from https://stackoverflow.com/a/16058059/6579265
*/
private static boolean isValidEmailAddress(String email) {
String ePattern = "^[a-zA-Z0-9.!#$%&'* /=?^_`{|}~-] @((\\[[0-9]{1,3}\\.[0-9]{1,3}"
"\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9] \\.) [a-zA-Z]{2,}))$";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
}
.
public class Password {
private static final String[] MANDATORY_CHARACTERS = { "!", "#", "$", "%", "^", "&", "*" };
private final String value;
private Password(String value) {
this.value = value;
}
public String value() {
return value;
}
public static Password of(final String pass) {
if (pass == null || pass.trim().isEmpty())
throw new InvalidAccountInformationException("Password cannot be empty.");
if (!containsAtLeastOneMandatoryCharacter(pass))
throw new InvalidAccountInformationException("Password is too weak.");
return new Password(pass);
}
private static boolean containsAtLeastOneMandatoryCharacter(String pass) {
return Stream.of(MANDATORY_CHARACTERS).anyMatch(pass::contains);
}
// Eclipse generated
@Override
public int hashCode() {
return Objects.hash(value);
}
// Eclipse generated
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Password other = (Password) obj;
return Objects.equals(value, other.value);
}
}
.
public class AccountDatabase {
private final List<Account> accounts = new ArrayList<>();
public void save(Account account) {
Objects.requireNonNull(account, "Account should not be null");
if (emailIsAlreadyTaken(account))
throw new InvalidAccountInformationException("Email is already taken by another user.");
accounts.add(account);
}
private boolean emailIsAlreadyTaken(Account account) {
return accounts.stream().map(Account::getEmail).anyMatch(account::equals);
}
}
然后,在 GUI (ActionListener) 中,代碼如下所示:
AccountDatabase database = ...
try {
Email email = Email.of(emailField.getText());
Password pass = Password.of(passwordField.getText());
Account account = new Account(email, pass);
database.save(account);
} catch (InvalidAccountInformationException ex) {
showToUser(ex.getMessage());
resetTextFieldsToEmptyTextSoUserCanFillThemAgain();
}
你取得了什么成就?始終保持一致的狀態!您的應用程式絕不會允許無效密碼。您想添加或洗掉密碼驗證,如長度等?您編輯 Password 類。不是一些奇怪的,充滿噪音的課程。您的 GUI 對包含實際邏輯的此類進行簡單呼叫。
此外,您還可以實作可測驗性。您將如何以自動化方式測驗您的 GUI 代碼?這是一個復雜的話題,而且肯定不是通過 UI 測驗應用程式邏輯的最佳方式。將邏輯和規則提取到其他類,您可以“只測驗它們”:
public class PasswordShould {
@Test
void not_be_valid_when_is_empty() {
assertThrows(RuntimeException.class, () -> Password.of(null));
assertThrows(RuntimeException.class, () -> Password.of(""));
assertThrows(RuntimeException.class, () -> Password.of(" "));
}
@Test
void not_be_valid_when_is_weak() {
assertThrows(RuntimeException.class, () -> Password.of("1234"));
assertThrows(RuntimeException.class, () -> Password.of("GGfdsfds12312"));
}
@Test
void be_valid_when_is_strong() {
assertDoesNotThrow(() -> Password.of("GGf##dsfds12312"));
}
}
我的代碼可能需要消化很多,但我建議嘗試理解它。首先,看一下可讀性。您來到這里,是因為您無法除錯自己的代碼。嗯......我們也不能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/429885.html
上一篇:無法在java.swing中為我的計時器更新分鐘和小時的JLabels
下一篇:MacOSX上的JTable多選
