黑马程序员技术交流社区

标题: 求大神解答,while循环字符数组角标越界的问题 [打印本页]

作者: Observer    时间: 2016-7-30 22:06
标题: 求大神解答,while循环字符数组角标越界的问题
[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=='\n') {
                                break;
                        }else if (ch>='a'&&ch<='z'||ch>='A'&&ch<='Z') {
                                countLetter++;
                        }else if (ch>='0'&&ch<='9') {
                                countNumber++;
                        }else if (ch==' ') {
                                countSpace++;
                        }else {
                                countOther++;
                        }
                        i++;
                }*/
                int i = 0;
                while (ch!='\n') {   //i<ch.length
                        if (ch>='a'&&ch<='z'||ch>='A'&&ch<='Z') {
                                countLetter++;
                        }else if (ch>='0'&&ch<='9') {
                                countNumber++;
                        }else if (ch==' ') {
                                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'该怎么写;


作者: 王清术    时间: 2016-7-30 22:16
不会保存'/n'。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2