java请任意东西,统计空格,并存入numbers[]数组中

来源:百度知道 编辑:UC知道 时间:2024/06/23 06:47:53
import java.util.Scanner;
public class aa
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
String line;
System.out.println("请任意东西,统计空格,并存入numbers[]数组中");
line = scanner.nextLine();
char[] figures = line.toCharArray();
char[] spaces={' '};
String numbers[] = String.valueOf(' ');
int count=0;
for (int i=0;i<figures.length;i++)
{if (figures[i]==spaces[0])
{
count++;

}
}
System.out.println("空格有" + count);
for (int j=0;j<numbers.length;j++)
{
System.out.println("numbers[" +j+ "]" +numbers[j]);
}
}
}
有错误,请问如何改,不用正则表达式

空格怎么保存在number数组中?
数组需要提前声明大小,在运行之前,你不可能知道有多少个空格。我不知道你是不是要统计每个空格出现的位置。
如果是这样,我帮你修改了一下:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CountSpace {

public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);
String line;
System.out.println("请任意东西,统计空格,位置存放在List之中。");
line = scanner.nextLine();
char[] figures = line.toCharArray();
char[] spaces = { ' ' };
List<Integer> sign = new ArrayList<Integer>();
int count = 0;
for (int i = 0; i < figures.length; i++) {
if (figures[i] == spaces[0]) {
count++;
sign.add(i);
}
}
System.out.println("空格有" + count);
System.out.println("---------空格位置----------");
for(Integer s :sign){
System.out.print(s+" ");
}

}