检查数组的总和是否小于最大时间,如果是,则随机数的生成器将停止,输出将如下:
No of customer = 3
max time = 4;
customer 1 = 3
customer 2 = 1
total time = 4
//so the customer 3 a
class CstplangsBadango
package cstplangsbadango;
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class CstplangsBadango {
static int customer = 0;
static int maxTime = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rand = new Random();
System.out.print("Enter number of customer: ");
customer = sc.nextInt();
System.out.print("Enter number of Maximum time: ");
maxTime = sc.nextInt();
System.out.println(" ");
int[] cust = new int[customer];
int j = 0;
int sum = 0;
int sum1 = 0;
int chu = 0;
for (int i = 0; i < cust.length; i++) {
cust[i] = (int) randomFill();
j += 1;
sum += cust[i];
System.out.println("Customer #" + j + " = " + cust[i]);
}
System.out.println(" ");
System.out.println("Maximum time: " + sum);
}
public static double randomFill() {
Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
return randomNum;
}
}
答案 0 :(得分:2)
for (int i = 0; i < cust.length; i++) {
cust[i] = (int) randomFill();
}
for (int i = 0; i < cust.length; i++) {
int newSum = sum + cust[i];
if (sum < maxTime) {
sum = newSum;
} else if(sum == maxTime) {
sum = newSum;
break;
} else {
break;
}
j++;
System.out.println("Customer #" + j + " = " + cust[i]);
}
答案 1 :(得分:0)
您必须排除声明
j+=1;
sum += cust[i];
System.out.println("Customer #" + j + " = " + cust[i])
并在填充数组时在创建的循环下创建另一个循环
for(int i=0;i<cust.length;++i)
{
j+=1;
sum+=cust[i];
if(sum>=MAX_TIME)
{
i=cust.length;
System.out.println("Customer #" + j + " = " + cust[i]);
}
}
if(sum>MAX_TIME)
{
int subtractor=sum-MAX_TIME;
sum-=subtractor;
}