1

My assignment asks me to write a program that will let the user input 10 players' name, age, position, and batting average. The program should then check and display statistics of only those players who are under 25 years old and have a batting average of .280 or better, then display them in order of age.

I've written my code for the input section (where it'll store them in an array):

static int players[] = new int [10];
static String name[] = new String [10];
static double average [] = new double [10];
static int age[] = new int [10];
static String position[] = new String [10];

//method to input names of Blue Jays
public static void inputInfo() throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));       

    for(int i = 0; i < players.length; i++)
    {
        System.out.println("Enter player information.");

        System.out.println("Input first and last name: ");
        name [i] = br.readLine();

        System.out.println("Input position: ");
        position[i] = br.readLine();

        System.out.println("Input batting average (e.g. .246): ");
        String averageString = br.readLine();
        average [i] = Double.parseDouble(averageString);

        System.out.println("Input age: ");
        age[i] = br.read();

        System.out.println(" ");

    }   
}

My problem is the input. For the first player I input it shows me this (as it should):

Input first and last name: 
John Smith
Input position:
pitcher
Input batting average (e.g. .246): 
.300
Input age:
27

But my second input skips the name section completely and jumps to the position input. I can't really figure out why it's doing this! Can anyone help me out? Thanks in advance!

4

3 回答 3

8

read方法只读取输入的单个字符;您输入的其余行仍保留在流中。

当下一个循环开始时,readLine检测到它已经可以读取该行的其余部分,因此无需用户输入。它认为用户输入已经给出。

对于输入年龄,使用readLine代替read,您可以使用Double.parseDouble将结果String输入转换为double

于 2013-08-28T21:03:17.493 回答
1

当您在这里阅读时代时:

System.out.println("Input age: ");
age[i] = br.read();

用户按下 <Enter> 的换行符仍然存在。所以,当你回去做

System.out.println("Enter player information.");

System.out.println("Input first and last name: ");
name [i] = br.readLine();

换行符仍在缓冲区中,将在此处读取。

于 2013-08-28T21:05:00.377 回答
1

read() 一次只读取一个字符。当您在输入年龄后按下时,它会在末尾附加一个换行符,这会触发 .readLine() 的名称。

        System.out.println("Input age: ");
        age[i] = Integer.parseInt(br.readLine());
于 2013-08-28T21:05:34.477 回答