如何增加数组

时间:2014-03-28 19:08:19

标签: java

我不确定我的问题是否正确,但最初我在主要运行了5次。但我觉得do / while循环可以做同样的事情。但是现在我无法将阵列shotMade从shotsMade [0]更改为shotsMade [1]等,并将shotCount存储到它。它只会存储while循环的最后一次运行。我可以更改什么使这两个项目增加,以便方法仍然正确计算数据

import java.util.*;

public class Final {
public static void main(String[] args) {
    int myGameCounter = 1;  
    int [] shotsMade = new int [5];
    System.out.print("Enter Player's Free Throw Percentage: ");
    Scanner input = new Scanner(System.in);
    int percent = input.nextInt();


    //Game 
do{ 
    System.out.println("Game " + myGameCounter + ":");
    Random r = new Random();
    myGameCounter++;
    int shotCount = 0;
    for (int i = 0; i < 10; ++i){
        boolean in = tryFreeThrow(percent);
        if (in) {
        shotCount++;
        System.out.print("In" + " ");
        }
        else {
        System.out.print("Out" + " ");
        }
    }
    System.out.println("");
    System.out.println("Free throws made: " + shotCount + " out of 10");
    System.out.println("");
    shotsMade[0]= shotCount;// I need shotsMade[0] to change each loop, shotsMade[1], shotsMade[2], shotsMade[3], shotsMade[4]
} while (myGameCounter <=5);

    System.out.println("");
    System.out.println("Summary:");
    System.out.println("Best game free throws made: " + max(shotsMade));
    System.out.println("Worst game free throws made: " + min(shotsMade));
    System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 50");
    System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");    


  }      
    public static boolean tryFreeThrow(int percent) {
    Random r = new Random();
    int number = r.nextInt(100);
    if (number > percent){ 
         return false;
    }
    return true;
    }
    public static int average (int nums[]) {
    int total = 0;
    for (int i=0; i<nums.length; i++) {
        total = total + nums[i];
    }
    int average =  total*10 / nums.length;
    return average;
    }
    public static int sum(int nums[]) {
    int sum = 0;
    for (int i=0; i<nums.length; ++i) {
        sum += nums[i];
    }
    return (int)sum;
    }
    public static int max(int nums[]) {
    int max = nums[0];
    for (int i=1; i<nums.length; i++) {
        if (nums[i] > max) 
            max = nums[i];
    }
    return max;
    }
    public static int min(int nums[]) {
    int min = nums[0];
    for (int i=1; i<nums.length; i++) {
        if (nums[i] < min) 
            min = nums[i];
    }
    return min;
    }

}

1 个答案:

答案 0 :(得分:0)

两件事:

  1. 在您设置myGameCounter++;

    的位置下方移动shotsMade[]

    否则,您在第一场比赛结束前将游戏计数器增加到2。 它应该看起来像:

    shotsMade[myGameCounter-1]= shotCount; myGameCounter++; } while (myGameCounter <=5);

  2. 设置shotsMade[myGameCounter-1]= shotCount;而不是shotsMade[0]= shotCount;

    否则,您将覆盖shotsMade[0]

  3. 的值

    这样,您将重新使用计数器作为数组的索引。由于myGameCounter在每次游戏后(在您更改第1点之后)将增加1,并且从1开始,因此使用myGameCounter - 1将为您的数组shotsMade生成正确的索引。

相关问题