站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题求一个数组越界的小问题,!!

求一个数组越界的小问题,!!

摘要: 求一个数组越界的小问题,!!


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时程序就认为出现异常了??
看了好久不明白,请教各位哪错了.!~```





经测试,当输入的个数>=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);
}


在我的环境下一切正常。lz把错误信息贴出来看看。


编译可以通过的,就是测试时得出的结果不正确,,,

一楼的分析得没错..


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的就一直结果是数组越界,难道我机子有问题??


这样:

对控制台的输入,我们是按回车结束的。这个时候除了输入的字符串以外,输入流还附加了两个字符,这两个字符是ascii码13的回车和ascii码10的/n

附加/n的原因是它表达了字符串的结束

如:123456789
实际上输入流里有以下字符:123456789回车/n
在程序执行时,由于判断的是/n,所以就会多读入两个字符,也就出现了18个字符输入就提示已经有20个的情况


补充一下:
楼主输入的
1 2 3 4 5 6 7 8 9 10
这算是20个有效字符,还没有包括隐含的回车和/n


就象楼上说的
1 2 3 4 5 6 7 8 9 10
这是19个字符,其中包括9个空格


1 2 3 4 5 6 7 8 9 10
是20个,不是19个,其中9个空格,10算两个字符



明白了,多谢各位了..



↑返回目录
前一篇: 召集初级JAVA程序员,组建网络团队学习JAVA
后一篇: 照书上原样写的怎么会出错呢?