java对存储数组中的特定值进行排序和显示
在我的任务中,我应该制定一个帮助决定棒球运动员选秀的计划。该程序会提示侦察员输入有关玩家的信息,并将其存储在一个数组中。然后,它将检查阵列,并显示25岁以下的球员名单,平均打击率为0.280或以上。名单必须按年龄排序
哦,菜单是必需的
我的问题是,除了标题,它没有给我任何输出!这不是分拣吗?if语句无效吗?怎么了
玩家类如下所示:
public class players
{
String name;
String position;
int age;
double average;
}
这是我的代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BlueJays
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static players[] arr;
public static void main(String[] args) throws IOException
{
String quit = "n";
while("n".equals(quit))
{
//display menu
System.out.println("Toronto Blue Jays Drafting Program - Main Menu");
System.out.println("1) Input Blue Jays data");
System.out.println("2) Display possible draft choices");
System.out.println("3) Quit program");
System.out.print("Please choose an option by inputting the number of your choice: ");
String choiceString = br.readLine();
int choice = Integer.parseInt(choiceString);
if(choice == 1)
{
inputInfo();
}else if(choice == 2)
{
sortInfo();
}else if(choice == 3)
{
System.out.println("Are you sure you want to quit? (y/n) ");
quit = br.readLine();
}else
{
System.out.println("Not a valid option.");
}
}
}
//method to input names of Blue Jays
public static void inputInfo() throws IOException
{
players temp = new players();
System.out.print("How many players would you like to enter? ");
int x = Integer.valueOf(br.readLine()).intValue();
arr = new players[x];
//loop through players
for(int i = 0; i < arr.length; i++)
{
System.out.println("Enter player information.");
System.out.println("Input first and last name: ");
String name = br.readLine();
temp.name = name;
System.out.println("Input position: ");
String position = br.readLine();
temp.position = position;
System.out.println("Input batting average (e.g. .246): ");
String averageString = br.readLine();
temp.average = Double.parseDouble(averageString);
System.out.println("Input age: ");
temp.age = Integer.parseInt(br.readLine());
System.out.println(" ");
// Copy the software name and quantity to the global variables
arr[i] = temp;
}
}
//method to sort and display info
public static void sortInfo()
{
//sort by quantity
for(int i = 0; i < arr.length; i++)
{
for(int j = i+1; j < arr.length; j++)
{
if(arr[i].age > arr[j].age)
{
players temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
System.out.println("Draft Choices 2013");
//output
for(int i = 0; i < arr.length; i++)
{
if (arr[i].age <= 25 && arr[i].average >= 0.280)
{
System.out.println("Name: " + arr[i].name);
System.out.println("Age: " + arr[i].age);
System.out.println("Position: " + arr[i].position);
System.out.println("Batting average: " + arr[i].average);
System.out.println(" ");
}
}
}
}
我很快就要交给你了,所以任何帮助都将不胜感激!提前谢谢
# 1 楼答案
代码中可能导致您出现问题的WTF:
}
只创建一个
players
实例并重用它。因此,您没有(比如)20个不同的players
的数组,而是一个指向同一对象20次的数组(实例)。该实例数据将被持续覆盖,并且只保存您放入的最后一个播放机的数据,如果它有age > 25
,则不会由于您的筛选而打印任何记录将实例创建移动到
for
}