任务二:实现问题二关键算法
编写一个程序,该程序读取一个字符串,然后输出读取的空格数目。
注意:输入字符串的长度不超过 30 个字符(含空格)。
import java.util.Scanner; public class one { public static void main(String[] args) { System.out.println("请输入字符串"); Scanner sc=new Scanner(System.in); String s =sc.nextLine(); int l=s.length(); int sum=0; while(l>30) { System.out.println("请输入不超过 30 个字符的字符串"); s=sc.nextLine(); l=s.length(); } for (int i = 0; i < l; i++) { char c=s.charAt(i); if (c== ' ') sum++; } System.out.println(sum); } }