gpt4 book ai didi

java - for循环只循环1次JAVA?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:34:18 25 4
gpt4 key购买 nike

我在使用只循环 1 次的 for 循环方法时遇到了问题,问题是什么?在数组中完全没有问题,它能够打印我想要的值。

这是我的代码:

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);

}

最佳答案

其他人已经确定了您问题的原因。但是,他们建议的修复方法过于具体……而且很脆弱。 (用 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

无论逗号周围以及字符串开头和结尾处的空白字符如何,这都会使您的代码正常工作。稳健性很好,尤其是在实现成本几乎为零的情况下。

最后,您甚至可以用 Java 7 String switch 语句替换 if/else if/... 内容。

关于java - for循环只循环1次JAVA?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15059578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com