我正在处理的这个数组遇到了问题。在 for 循环中,我需要以某种方式计算基础百分比。索引 0 处的元素将存储 OBP。如何保留用户输入的用于计算 OBP 的信息?谢谢。
for (int index = 0; index < years.length; index++)
{
System.out.print("For Year " + (index +1 ) + "\nEnter number of hits: ");
years[index] = keyboard.nextInt();
System.out.print("For Year " + (index +1) + "\nEnter number of walks: ");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of times player"
+ "has been hit by a pitch:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of at bats:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of sacrafice flies"
+ "that year: ");
years[index] = keyboard.nextInt();
}
最佳答案
对于此用例,我建议在 HashMap 中使用 HashMap。
循环之前:
HashMap<Integer, HashMap<String, Integer>> years = new HashMap<>();
HashMap<String, Integer> entry = new HashMap<>();
对于用户键盘的每个输入(示例):
entry.put("hits", 5);
years.put(2019, entry);
entry.put("walks", 10);
years.put(2019, entry);
最终你会得到如下结果:
{2019={hits=5, walks=10}}
检索结果也很简单:
// retrieve map of data for a specific year:
years.get(2019)
result: {hits=5, walks=10}
// retrieve specific data for a specific year:
years.get(2019).get("hits")
result: 5
关于java - 如何计算数组的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978137/