我遇到了一个问题,for循环方法只循环1次,这是什么问题?在数组中没有任何问题,它可以打印出我想要的值。
下面是我的代码:
public static void main(String[] args){
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++){
if(word[y].toString().equals("Apple2") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple3") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple4") ){
total++;
//str.append(word[y].toString());
}
else if(word[y].toString().equals("Apple1") ){
total++;
//str.append(word[y].toString());
}
}
System.out.println( word[0] + word[1] + word[2] + word[3] + word[4] + word.length);
System.out.println(str + "hihi" + total);
}发布于 2013-02-25 11:26:12
尝试在", "上拆分(带空格)
String[] word = s.split(", ");如果拆分中没有这个空格,word[1]将看起来像" Apple1"而不是"Apple1"
另一种选择是调用word[y].trim().equals("Apple2")来消除额外的空间,但我会说将其包含在split中会更好。如果您不确定逗号附近可以有多少空格,您可以这样拆分split("\\s*,\\s*"),以包含逗号周围的所有空格。
同样,正如Matt Ball在他的评论中指出的那样,你不需要在word[y]上调用toString(),因为它已经是字符串了。
发布于 2013-02-25 11:36:15
其他人已经找到了你问题的原因。然而,他们建议的修复方法太具体了.也很脆弱。(使用split("\\s*,\\s*")拆分更好,但它不能处理整个字符串开头/结尾的空格。)
我建议你继续使用split(","),但在测试之前先修剪一下;
for (int y = 0; y < word.length; y++) {
String trimmed = word[y].trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera或者更好的是:
String[] words = s.split(",");
for (String word : words) {
String trimmed = word.trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera这将使您的代码正常工作,而无需考虑逗号周围以及字符串开头和结尾的空格字符。健壮性是好的,特别是如果它的实现成本几乎为零。
最后,您甚至可以替换if / else if / ...填充Java 7字符串switch语句。
发布于 2013-02-25 11:28:01
在拆分过程中忽略该空间。String[] word = s.split(",");
https://stackoverflow.com/questions/15059578
复制相似问题