-1

大家好,我对这段代码有点卡住了。除了我希望随机数加起来达到用户定义的数量外,我已经全部搞定了。例如,用户输入 23500 我希望所有随机数加起来为总数。这就是我到目前为止所拥有的

package containerweights;
import java.util.Random;
import java.util.Scanner;
import java.io.*;
public class Containerweightgenerator {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);
        System.out.printf ("%n ***Random Number Genreator*** %n%n");
        System.out.print("Enter total: ");
        double total_weight = input.nextDouble();
        System.out.print("Enter amount: ");
        double total_pallets = input.nextDouble();

        double average_weight = total_weight / total_pallets;
        System.out.printf("%-40s -%10.2f%n", "Average Weight is: ", average_weight);

        double first_weight = average_weight - 50;
        double second_weight = average_weight + 50;

        double START = first_weight;
        double END = second_weight;
        Random random = new Random();
        for (int idx = 1; idx <= total_pallets; ++idx)
        {
            showRandomInteger(START, END, random);
        }
        }
    private static void showRandomInteger(double sTART, double eND, Random aRandom) throws Exception{
        if ( sTART > eND )
        {
            throw new Exception(" Start connot exceed End.");
        }
        long range = (long)eND - (long)sTART + 1;

        long fraction = (long)(range * aRandom.nextDouble());
        int randomNumber = (int)(fraction + sTART);
        System.out.println(randomNumber);
    } 
        private static void log(String aMessage)
        {
            log(aMessage);
        }   
    }
4

2 回答 2

4

只是给出随机数。如果您给出的最后一个数字超过总数,则返回与总数的差值而不是该数字

根据新要求,我编辑了对以下内容的回答:

int pallets=10;
int targetWeight=100;
int totalSoFar = 0;
int[] palletWeight = new int[pallets];

//Give random weight to N-1 pallets
for (int i=0; i<pallets-1; ++i){
    palletWeight[i] = random.nextInt(1.33 * targetWeight / pallets);
    totalSoFar += palletWeight[i];
}

//Check if we exceeded our target
if (totalSoFar > targetWeight){    
    while(totalSoFar > targetWeight){
      int x = random.nextInt(pallets - 1); //pick a pallet at random
      int a = random.nextInt(palletWeight[x]);
      palletWeight[x] -= a; //take of a random 'a' grams out of its weight
      totalSoFar -= a;
    }
}
//Now we are under the target weight, let the last pallet be the difference
 palletWeight[pallets-1] = targetWeight - totalSoFar;
于 2013-04-08T12:01:29.880 回答
1

如果 Lefteris 的答案对您不起作用(因为可能要求所有值实际上都是“随机的”——抛开这意味着什么),您唯一的选择是重复生成随机数集并将它们相加。

这又丑又慢,我更喜欢 Lefteris 的回答。但他确实意味着该系列中的最后一个数字不会是随机的,它的大小分布可能会使其脱颖而出。

于 2013-04-08T12:58:06.713 回答