Generating random numbers until sum is 1000

时间:2018-03-22 23:50:36

标签: java arrays loops do-while

I am new to Java and programming overall. I am currently attending an introductory class to object oriented programming and need some help in writing a code. The program I am writing is for a dart game. I am supposed to randomly generate the number of times the dart hits a certain area of the board and store it into one array. Then in another array, I have to keep track of the scores. the scores should add up to a total of 1000 or over but I am having problem doing that. My program works fine but it does show the result even when the sum is under 1000. I even tried using do-while loop but i don't seem to get the right answer. Also I need help with shortening the lines 18-27. Here's my code, any kind of help is appreciated.

import java.util.Arrays;
import java.util.Random;
public class Assignment3Q1
{
public static void main(String[] args)
{
    Random darts = new Random();
    int [] timesHit = new int [10];
    int sum=0;
    int tosses=0;
    do
    {
        for ( int i = 0; i < timesHit.length; i++)  
        {
            timesHit[i]= 20 + darts.nextInt(20);
        }
        int [] points = new int [10];
        points [0] = timesHit[0]*7;
        points [1] = timesHit[1]*5;
        points [2] = timesHit[2]*5;
        points [3] = timesHit[3]*5;
        points [4] = timesHit[4]*3;
        points [5] = timesHit[5]*3;
        points [6] = timesHit[6]*3;
        points [7] = timesHit[7];
        points [8] = timesHit[8];
        points [9] = timesHit[9];
        for (int i=0; i<timesHit.length; i++)
        {   
            tosses += timesHit[i];
        }
        for (int i=0; i<points.length; i++)
        {
            sum += points[i];
        }
        System.out.println(tosses);
        System.out.println(sum);
        break;
    }while (sum>=1000);
}

}

1 个答案:

答案 0 :(得分:0)

Here is the correct logic to keep looping until the desired result (sum >= 1000). Also notice the use of the multiplier array so that the points can be calculated in the hit loop. The other two sums can also be done in the same loop.

public class Assignment3Q1 {
   public static void main(String[] args)
    {
        Random darts = new Random();
        int sum=0;
        int tosses=0;
        int multiplier[] = {7, 5, 5, 5, 3, 3, 3, 1, 1, 1};
        do
        {
            int [] timesHit = new int [10];
            int [] points = new int [10];
            tosses = 0;
            sum = 0;
            for ( int i = 0; i < timesHit.length; i++)  
            {
                timesHit[i]= 20 + darts.nextInt(20);
                points[i] = timesHit[i] * multiplier[i];
                tosses += timesHit[i];
                sum += points[i];
            }
        } while (sum<1000);
        System.out.println("Final Tosses="+tosses);
        System.out.println("Final Sum="+sum);
    }

}