代码复制如下。如果字符变量l等于空格,它应返回空格数,但始终返回0.
我用字母对它进行了测试并且它有效,例如,如果我要求它在变量l等于e时递增并输入带有e in的句子,它将计算它。但出于某种原因,不是空格。
import java.util.Scanner;
public class countspace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = input.next();
System.out.println(wc(str));
}
public static int wc(String sentence) {
int c = 0;
for (int i = 0; i < sentence.length(); i++) {
char l = sentence.charAt(i);
if (l == ' ') {
c++;
}
}
return c;
}
}
答案 0 :(得分:3)
答案 1 :(得分:2)
请改用nextLine
。您还可以打印行进行调试:
System.out.println(str);
答案 2 :(得分:1)
使用字符串str = input.nextLine()
;而不是字符串str = input.next();
这是你应该做的方式来获得下一个字符串。
您可以检查str的值是否正确。