Java 测试帐号中是否只有一个连字符
我想只使用字符串方法重写下面的代码,而不使用for循环Java 测试帐号中是否只有一个连字符,java,oop,Java,Oop,我想只使用字符串方法重写下面的代码,而不使用for循环 // 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. pr
// 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;
}
//运行QuestionGenerator并测试错误条件
//表明。如果帐号的格式有效
//根据问题生成器中列出的要求,返回
//正确,否则错误。
私有静态布尔值isAccountFormatCorrect(字符串名称){
int m=0;
对于(int i=0;i=2){
抛出新的BadAccountInputException(“帐号中只允许一个连字符”);
}
返回true;
}
将连字符的第一个索引与找到它的最后一个索引进行比较。如果它们相等,那么只有一个
private static boolean isAccountFormatCorrect(String name) {
if(name.indexOf('-') != name.lastIndexOf('-')){
throw new BadAccountInputException("Only one hyphen allowed in account number");
}
return true;
}
但是,您似乎希望返回一个布尔值,指示帐户是否有效,在这种情况下,不需要抛出异常
private static boolean isAccountFormatCorrect(String name) {
return name.indexOf('-') == name.lastIndexOf('-');
}
如果需要确保只有一个连字符,则需要检查索引是否为非-1
private static boolean isAccountFormatCorrect(String name) {
int idx = name.indexOf('-');
return idx != -1 && idx == name.lastIndexOf('-');
}
那么你的问题是什么?请提供您尝试做的事情和得到的结果的示例。此外,您从不返回false,而是抛出异常。您也可以只检查for循环本身是否有多个连字符,使用一个布尔值告诉您是否已经遇到了一个连字符。另一种方法是在字符串中找到
-
的第一个和最后一个索引,并确保它们相等。使用string.indexOf('-')和string.lastIndexOf('-')更好的方法是返回name.indexOf('-')!=name.lastIndexOf('-')
。不需要抛出异常-这违反了方法约定。@实际上,在这种情况下最好不要抛出任何异常。如果字符串没有破折号,测试将返回true-1==-1。@GilbertLeBlanc问题中的方法也是如此。@user好的。