import java.io.IOException;
public class CharArray{
public static void main(String args[])
{
System.out.println("请输入数组元素:");
try
      {
        String s=getInput();
        System.out.println(s);
  }
   catch(IOException e)
{
   System.out.println(e.getMessage());
}
}
static String getInput() throws IOException
{
char[] buffer=new char[20];
int counter=0;
boolean flag=true;
while(flag)
{
buffer[counter]=(char)System.in.read();
if(buffer[counter]=='\n')
flag=false;
counter++;
if(counter>=20)
{
IOException ae=new IOException("数组越界");
throw ae;
}
}
return new String(buffer);
}
}////
我运行后测试发现当输入的数的个数不大于8时程序正常,但当个数大于8时程序就认为出现异常了??
看了好久不明白,请教各位哪错了.!~```

解决方案 »

  1.   

    经测试,当输入的个数>=19个的时候会出现数组越界异常而并不是if(count>=20)才出现越界分析原因是count++;这句代码在if(count>=20)判断之前,每次判断之前都先加了一,所以会少一位就越界,应该把判断放在循环的最开始:
        while (flag) {
          if (counter >= 20) {
            IOException ae = new IOException("数组越界");
            System.out.println("counter=" + counter);
            throw ae;
          }      buffer[counter] = (char) System.in.read();
          if (buffer[counter] == '\n')
            flag = false;
          counter++;      System.out.println("counter="+counter);
        }
      

  2.   

    import java.io.IOException;
    public class CharArray{
    public static void main(String args[])
    {
    System.out.println("请输入数组元素:");
    try
          {
            String s=getInput();
            System.out.println(s);
      }
       catch(IOException e)
    {
       System.out.println(e.getMessage());
    }
    }
    static String getInput() throws IOException
    {
    char[] buffer=new char[20];
    int counter=0;
    boolean flag=true;
    while(flag)
    {
                      if(counter>=20)
    {
    IOException ae=new IOException("数组越界");
    throw ae;
    } buffer[counter]=(char)System.in.read();
    if(buffer[counter]=='\n')
    flag=false;
    counter++;
    }
    return new String(buffer);
    }
    }
    =============================
    测试结果:
    请输入数组:
    1 2 3 4 5 6 7 8 9 10
    数组越界
    ========接下来>10的就一直结果是数组越界,难道我机子有问题??
      

  3.   

    这样:对控制台的输入,我们是按回车结束的。这个时候除了输入的字符串以外,输入流还附加了两个字符,这两个字符是ascii码13的回车和ascii码10的\n附加\n的原因是它表达了字符串的结束如:123456789
    实际上输入流里有以下字符:123456789回车\n
    在程序执行时,由于判断的是\n,所以就会多读入两个字符,也就出现了18个字符输入就提示已经有20个的情况