我需要帮助处理eclipse中遇到的checkstyle错误。我已经尝试了我的布尔方法中的错误。它声明我的嵌套if else在它应该为零时为1。这适用于我所有的if语句。我遇到的另一个错误是我的方法有3个返回,checkstyle说最大值是2.我只是想摆脱这些错误,有人可以帮助我。
public class Password {
private String potentialpassword;
private static final String SPECIAL_CHARACTERS = "!@#$%^&*()~`-=_+[]{}|:\";',./<>?";
/**
* initializes the potential password and takes it as a string.
*
* @param potentialpassword
* takes in the potential password
*
*/
public Password(String potentialpassword) {
super();
this.potentialpassword = potentialpassword;
}
/**
* The purpose of this method is to validate whether the password meets the
* criteria that was given
*
* @param potentialpassword
* allows a string potential password to be accepted.
* @return true or false if the method fits a certain guideline.
* @precondition password has to be greater than 6 characters long. password
* also cannot contain any whitespace and the digits cannot be
* less than one.
*/
public static boolean isValid(String potentialpassword) {
if (potentialpassword.length() < 6) {
return false;
} else {
char x;
int count = 0;
for (int i = 0; i < potentialpassword.length(); i++) {
x = potentialpassword.charAt(i);
if (SPECIAL_CHARACTERS.indexOf(String.valueOf(x)) >= 1) {
return true;
}
if (Character.isWhitespace(x)) {
return false;
}
if (Character.isDigit(x)) {
count++;
} else if (count < 1) {
return false;
}
}
return true;
}
}
/**
* Print the potential string characters on a separate line.
*
* @return the potential password characters on each line.
*
*
*/
public String toString() {
String potentialpassword = "w0lf@UWG";
for (int i = 0; i < potentialpassword.length(); i++) {
System.out.println(potentialpassword.charAt(i));
}
return potentialpassword;
}
}
答案 0 :(得分:2)
样式检查员可以抱怨很多。您可以通过将其设置更改为不那么挑剔来安静下来,或者您可以处理其中的一些建议。在你的情况下,它不喜欢太多的嵌套,它不喜欢多次返回。
else
之后return
可能是一个问题,所以你可以说
if (potentialpassword.length() < 6) {
return false;
}
char x;
int count = 0;
for (int i = 0; i < potentialpassword.length(); i++) {
.
.
.
减少嵌套。如果多个return语句更有问题,您可以尝试:
// NOTE I am just copying over your code and not worrying about the algorithm's correctness
boolean valid = true;
if (potentialpassword.length() < 6) {
valid = false;
} else {
char x;
int count = 0;
for (int i = 0; i < potentialpassword.length(); i++) {
x = potentialpassword.charAt(i);
if (SPECIAL_CHARACTERS.indexOf(String.valueOf(x)) >= 1) {
valid = true;
break;
}
if (Character.isWhitespace(x)) {
valid = false;
break;
}
if (Character.isDigit(x)) {
count++;
} else if (count < 1) {
valid = false;
break;
}
}
return valid;
}
减少了return
语句的数量,但嵌套级别保持较高。将代码分解为更小的方法可能有所帮助:
public static boolean isValid(String potentialpassword) {
return potentialpassword.length >= 6 &&
containsAtLeastOneSpecialCharacter(potentialpassword) &&
!containsWhitespace(potentialpassword) &&
startsWithADigit(potentialpassword);
}
然后你没有嵌套,但代码效率稍差,因为你在整个字符串上运行每个测试。而且你会有更多的代码行。不过我会想象checkstyle会更安静。