gpt4 book ai didi

java - 数组和输入

转载 作者:行者123 更新时间:2023-11-29 09:54:41 24 4
gpt4 key购买 nike

我的作业要求我编写一个程序,让用户输入 10 名球员的姓名、年龄、位置和平均击球率。然后程序应该只检查和显示 25 岁以下且平均安打率为 0.280 或更高的球员的统计数据,然后按年龄顺序显示。

我已经为输入部分编写了代码(它将把它们存储在一个数组中):

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(" ");

}
}

我的问题是输入。对于我输入的第一个玩家,它向我显示了这个(它应该如此):

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

但是我的第二个输入完全跳过了名称部分并跳转到了位置输入。我真的不明白为什么要这样做!谁能帮我吗?提前致谢!

最佳答案

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

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

对于输入的年龄,使用readLine代替read,并且可以使用Double.parseDouble转换结果String 输入一个 double

关于java - 数组和输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18498085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com