[Java] 纯文本查看 复制代码 package com.heima.test;
import java.util.Scanner;
public class Test07{
/*
*题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
1.程序分析:利用while语句,条件为输入的字符不为'\n'.
*/
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("输入一行字符");
String str = sc.nextLine();
count(str);
}
//统计输入的字符数
private static void count(String str) {
//计数器
int countLetter = 0;
int countSpace = 0;
int countNumber =0;
int countOther = 0;
//将字符串转成字符数组存储
char[] ch = str.toCharArray();
/* for (int j = 0; j < ch.length; j++) {
if (ch[i]=='\n') {
break;
}else if (ch[i]>='a'&&ch[i]<='z'||ch[i]>='A'&&ch[i]<='Z') {
countLetter++;
}else if (ch[i]>='0'&&ch[i]<='9') {
countNumber++;
}else if (ch[i]==' ') {
countSpace++;
}else {
countOther++;
}
i++;
}*/
int i = 0;
while (ch[i]!='\n') { //i<ch.length
if (ch[i]>='a'&&ch[i]<='z'||ch[i]>='A'&&ch[i]<='Z') {
countLetter++;
}else if (ch[i]>='0'&&ch[i]<='9') {
countNumber++;
}else if (ch[i]==' ') {
countSpace++;
}else {
countOther++;
}
i++;
}
System.out.println("字母"+countLetter);
System.out.println("数字"+countNumber);
System.out.println("空格"+countSpace);
System.out.println("其他"+countOther);
}
}
能用for循环得到结果
但题目按要求用利用while语句,条件为输入的字符不为'\n',不会做,出现了角标越界
问题1:键盘录入字符串的时候,会保存'\n'吗
问题2:按分析的要求用到'\n'该怎么写;
|