package code;
public class WriteUp{
public boolean containsNoDigits(String s){
s = s.toLowerCase();
char[] n = {'0', '1', '2', ....., '9'} //i wrote out 0-9
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (c == n[i]);
return false; //if string contain digit
}
return true; //if string contain NO digit
}
}我想编写一个方法(使用Array)来检查我的字符串是否包含一个数字。数字=>假;没有数字=>真;
我的代码未能通过JUnit测试
JUnit测试:
@Test
public void test(){
code.WriteUp wu = new code.WriteUp();
boolean expected = true;
boolean actual = wu.containsNoDigits("there is no digit")
assertTrue("", expected ==actual);
}
@Test
public void test01(){
code.WriteUp wu = new code.WriteUp();
boolean expected = false;
boolean actual = wu.containsNoDigits("there are digit, 0342432")
assertTrue("", expected ==actual);
}如何修正代码,使其正确工作?
发布于 2015-03-09 22:27:58
在再次仔细阅读我的代码之后,我能够知道为什么我搞砸了,并想出了一个解决方案。
public boolean containsNoDigits(String s) {
s = s.toLowerCase();
char[] n = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == n[0] || c == n[1] || c == n[2] || c == n[3] || c == n[4] ||
c == n[5] || c == n[6] || c == n[7] || c == n[8] || c == n[9]) {
return false; // if s has no digit
}
}
return true; // if s has digit
}感谢您提供更短、更有效的解决方案。我是个初学者,所以我编写了尽可能基本的代码,这个解决方案是为了更好地理解数组的使用。
发布于 2015-03-09 22:07:01
分号终止块,移除它。
if (c == n[i]); // <-- here
return false;实际上是
if (c == n[i]); // <-- here
return false;你需要类似的东西(最好用牙套)
if (c == n[i]) {
return false;
}或
if (c == n[i])
return false;此外,正则表达式将更有效。喜欢
public boolean containsNoDigits(String s){
return !s.matches("\\d"); // <-- digit pattern
} 发布于 2015-03-09 22:08:01
这应该是可行的:
public boolean hasDigit(String x){
for (char c : x.toCharArray())
if (Character.isDigit(c))
return false;
return true;
}您可以使用一个Character.isDigit(c)字符数组轻松地遍历字符串中的所有字符,并使用函数轻松地检查每个字符。这可能是最简单和最容易阅读。
希望这能有所帮助。
https://stackoverflow.com/questions/28952558
复制相似问题