通过数组打印适当的数字

时间:2019-05-11 11:22:14

标签: java printing

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

1 个答案:

答案 0 :(得分:1)

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

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

作者:

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