java - 通过数组打印适当的数字
问题描述
我正在尝试打印棒球运动员的基本百分比。到目前为止,代码运行良好。唯一的问题是,当我打印出每年的 OBP 时,我似乎无法匹配与用户输入的年份相关的正确年份。每次在 printOnBasePercentage() 方法中循环时,它都会将年份增加一。有没有办法解决这个问题?谢谢。
我试过添加+startYear++
,但似乎没有用。它让我更接近了。
public static void main(String[] args) {
int numYears;
double [] years;
String name;
int startYear;
double oBP;
int hits, walks, sacFlies, hitsByPitch, atBats;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of baseball player: ");
name = keyboard.nextLine();
System.out.print("Enter the number of years " + name +" has been playing: ");
numYears = keyboard.nextInt();
years = new double[numYears];
System.out.print("Enter " +name +" first year on the team: ");
startYear = keyboard.nextInt();
for (int index = 0; index < years.length; index++) {
System.out.print("For Year: "+ startYear++);
System.out.print("\nEnter how many hits the player has: ");
hits = keyboard.nextInt();
System.out.print("Enter the number of walks the player has: ");
walks = keyboard.nextInt();
System.out.print("Enter the number of sacrifice flies the player has: ");
sacFlies = keyboard.nextInt();
System.out.print("Enter the number of hits by pitch the player has: ");
hitsByPitch = keyboard.nextInt();
System.out.print("Enter the amount of at bats the player has: ");
atBats = keyboard.nextInt();
years[index] = ((hits + walks + hitsByPitch) / atBats+ walks+ hitsByPitch +sacFlies);
}
printOnBasePercentage(name, startYear, years);
}
public static void printOnBasePercentage(String name, int startYear, double []years){
for (int index = 0; index < years.length; index++){
System.out.println("\n" + name + "'s On Base Percentage");
System.out.printf("For Year: " +startYear + " " + "%.3f", years[index]);
}
}
解决方案
问题是您在两个循环中都使用了一个可变变量。在 main 方法中,您增加startYear
变量,然后在printonBasePercentage
方法中传递此更改的变量。尝试替换这一行:
System.out.print("For Year: "+ startYear++);
经过:
System.out.print("For Year: "+ startYear + index);
推荐阅读
- swift - 如何从集合视图中删除元素 [Swift]
- java - Wikipedia API 获取随机文章
- ruby - 函数参数中的 Ruby 解构
- node.js - 是否可以从 jasmine 测试中执行 newman 集合
- jquery - 带有 flexslider 和 elevatezoom 的动画错误
- android - 如何从firebase数据库中具有多个子节点的多个节点检索数据
- html - CSS - 如何使在我的输入中输入的文本开始显示在框的左上角?
- javascript - 如何使用javascript反转xml的顺序
- dropbox-api - 将 Dropbox 文件路径正确转换为小写
- xml - 使用 xpath 从 xml 中提取值