有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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]);
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    你的问题是,当你只做br.read()时,它的行为与readLine()不同readLine()读取并包含新行,但从响应中删除新行。因此,如果输入“名称<;新行>;”返回“名称”,但“<;新行>;”被消耗掉了。但是,read()只读取一个字符,其余字符保持原样,因此当您输入“b<;新行>;”当“<;新行>;”时返回b'留在输入流中。因此,下次您使用readLine来询问姓名时,输入将被解析到下一个“”,这恰好是输入性别时留下的新行,前面没有字符,因此返回一个空字符串

    您可以使用现有程序和以下输入进行测试:

    3
    name1
    bname2
    gname3
    b
    

    因此,你需要确保新行已被使用,或许可以在阅读性别后使用br.readLine()。如果你试图通过读一个额外的字符来消耗新行,请注意,在某些系统中,新行实际上是两个字符

  2. # 2 楼答案

    这里的问题是输入的方式。 将do while循环更改为:

    do {
            System.out.println("enter the data of " + (i + 1) + " student");
            c[i] = br.readLine();
            s[i] = (char) br.read();            
            br.readLine();       // even a br.read(); would work. Used to read newline
            i++;
       } while (i < n);