首页 > 解决方案 > 通过数组打印适当的数字

问题描述

我正在尝试打印棒球运动员的基本百分比。到目前为止,代码运行良好。唯一的问题是,当我打印出每年的 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]);
    }
}

标签: javaprinting

解决方案


问题是您在两个循环中都使用了一个可变变量。在 main 方法中,您增加startYear变量,然后在printonBasePercentage方法中传递此更改的变量。尝试替换这一行:

System.out.print("For Year: "+ startYear++);

经过:

System.out.print("For Year: "+ startYear + index);

推荐阅读