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时程序就认为出现异常了??
看了好久不明白,请教各位哪错了.!~```
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时程序就认为出现异常了??
看了好久不明白,请教各位哪错了.!~```
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);
}
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的就一直结果是数组越界,难道我机子有问题??
实际上输入流里有以下字符:123456789回车\n
在程序执行时,由于判断的是\n,所以就会多读入两个字符,也就出现了18个字符输入就提示已经有20个的情况