java数组和循环情况
我们收到了一个关于制作一个程序的问题,该程序用于输入人名和性别(n编号),并将男孩和女孩存储在两个单独的数组中。我编写了以下代码,但它不接受第二个循环中的名称和性别。为什么
import java.io.*;
class arrays
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void main()throws IOException
{
String name="";
System.out.println("enter number of students");
int n=Integer.parseInt(br.readLine());
String[] c=new String[n];//5
String[] b=new String[n];//5
String[] g=new String[n];//5
char[] s=new char[n];
System.out.println("enter the name and gender of "+n+" students");
int i=0;
do
{
System.out.println("enter the data of "+(i+1)+" student");
c[i]=br.readLine();
s[i]=(char)br.read();
i++;
}
while(i<n);
for(int j=0;j<n;j++)
{
if(s[j]=='b'||s[j]=='B')
{
System.arraycopy(c,j,b,j,1);
}
else if(s[j]=='g'||s[j]=='G')
{
System.arraycopy(c,j,g,j,1);
}
}
for(int j=0;j<n;j++)
{
System.out.print("boys are:-"+b[j]);
System.out.println("girls are:-"+g[j]);
}
}
}
# 1 楼答案
你的问题是,当你只做
br.read()
时,它的行为与readLine()
不同readLine()
读取并包含新行,但从响应中删除新行。因此,如果输入“名称<;新行>;”返回“名称”,但“<;新行>;”被消耗掉了。但是,read()只读取一个字符,其余字符保持原样,因此当您输入“b<;新行>;”当“<;新行>;”时返回b'留在输入流中。因此,下次您使用readLine来询问姓名时,输入将被解析到下一个“”,这恰好是输入性别时留下的新行,前面没有字符,因此返回一个空字符串您可以使用现有程序和以下输入进行测试:
因此,你需要确保新行已被使用,或许可以在阅读性别后使用
br.readLine()
。如果你试图通过读一个额外的字符来消耗新行,请注意,在某些系统中,新行实际上是两个字符# 2 楼答案
这里的问题是输入的方式。 将do while循环更改为: