英文:
Test for the presence of only one hyphen in the account number
问题
我想使用只有字符串方法而没有for循环来重写以下代码。
private static boolean isAccountFormatCorrect(String name) {
int m = name.length() - name.replace("-", "").length();
if (m >= 2) {
throw new BadAccountInputException("Only one hyphen allowed in account number");
}
return true;
}
英文:
I would like to rewrite the following code using only String methods, without for loops.
// Run the QuestionGenerator and test for the error condition
// indicated. If the account number has a valid format
// according to the requirement set out in the question generator, return
// true, otherwise false.
private static boolean isAccountFormatCorrect(String name) {
int m = 0;
for(int i = 0; i < name.length(); i++) {
char a = name.charAt(i);
if (a == '-') {
m++;
}
}
if (m >= 2) {
throw new BadAccountInputException("Only one hyphen allowed in account number");
}
return true;
}
答案1
得分: 1
Compare the first index of a hyphen with the last index where it is found. If they are equal, then there was only one.
private static boolean isAccountFormatCorrect(String name) {
if(name.indexOf('-') != name.lastIndexOf('-')){
throw new BadAccountInputException("Only one hyphen allowed in account number");
}
return true;
}
However, it seems you want to return a boolean indicating whether or not the account is valid, in which case there is no need to throw exceptions.
private static boolean isAccountFormatCorrect(String name) {
return name.indexOf('-') == name.lastIndexOf('-');
}
If you need to ensure there is exactly one hyphen, you will need to check that the index is not -1.
private static boolean isAccountFormatCorrect(String name) {
int idx = name.indexOf('-');
return idx != -1 && idx == name.lastIndexOf('-');
}
英文:
Compare the first index of a hyphen with the last index where it is found. If they are equal, then there was only one.
private static boolean isAccountFormatCorrect(String name) {
if(name.indexOf('-') != name.lastIndexOf('-')){
throw new BadAccountInputException("Only one hyphen allowed in account number");
}
return true;
}
However, it seems you want to return a boolean indicating whether or not the account is valid, in which case there is no need to throw exceptions.
private static boolean isAccountFormatCorrect(String name) {
return name.indexOf('-') == name.lastIndexOf('-');
}
If you need to ensure there exactly one hyphen, you will need to check that the index of not -1.
private static boolean isAccountFormatCorrect(String name) {
int idx = name.indexOf('-');
return idx != -1 && idx == name.lastIndexOf('-');
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论