我如何编写一个for循环来打印用户输入的字符串中的空格量?在我的for循环中,当我编写if(ch ==“”)时,编译器会说“无法比较的类型:char和java.lang.String”。当我编码(ch =='')时,它表示“未封闭的字符文字”。提前谢谢
import java.util.Scanner;
public class Count{
public static void main (String[] args){
Scanner scan = new Scanner (System.in);
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
int i = 0;
char ch; // an individual character in the string
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine(); // read input Scanner
// Find the length of the phrase
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
// and count the blank spaces
for (i = 0; ch < length; i++){
ch = phrase.charAt(i);
if (ch == ' ')
countBlank++;
}
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}