写一个while循环,选择并显示一个随机的两个数字组(1-99),当它们加在一起时可以被7整除。继续直到用户说他们已经“完成”。
我不知道如何使这两个随机数与7平分 我试过if语句,但它仍然不起作用。
这是我到目前为止所得到的:
public static void main(String []args)
{
Scanner scan= new Scanner (System.in);
String answer="Yes";
System.out.println("Run the program?");
answer= scan.nextLine();
while(!answer.equalsIgnoreCase("done") )
{
int a=1;
int b=1;
a=(int) (Math.random()*99) + 1;
b=(int) (Math.random()*99) + 1;
if ((a + b) % 7 == 0)
{
System.out.println(a + " + " + b + "= " +(a+b));
}
System.out.println("Do you want to continue?");
answer= scan.nextLine();
}
答案 0 :(得分:1)
首先,我更喜欢Random.nextInt(int)
,因为它更容易阅读(和使用)。然后,您可以使用b
modulo a + b
的结果调整7
(因为这是余数)。像,
Random rand = new Random();
while (!answer.equalsIgnoreCase("done")) {
int a = 1 + rand.nextInt(99);
int b = 1 + rand.nextInt(99);
// Updated based on @JimGarrison's comment.
if (b < 7) {
b = 7 - a;
} else if (b > 93) {
b = 98 - a;
} else {
b -= (a + b) % 7;
}
System.out.println(a + " + " + b + " = " + (a + b));
System.out.println("Do you want to continue?");
answer = scan.nextLine();
}
答案 1 :(得分:0)
由于它是随机的,所以得到(a + b)%7!= 0的情况可能会占用很多。
所以我认为这效率不高:
Scanner scan = new Scanner(System.in);
String answer = "Yes";
System.out.println("Run the program?");
answer = scan.nextLine();
int LIMIT = 99;
List<Integer> divisible7List = new ArrayList<Integer>();
// Generate elements that divisible by 7 that less than 99 + 99
int count = 1;
int divisible7 = 7 * count;
int maxDivisible7 = LIMIT + LIMIT;
while (divisible7 < maxDivisible7) {
divisible7List.add(divisible7);
divisible7 = 7 * (++count);
}
int size = divisible7List.size();
StringBuilder sb = new StringBuilder();
Random rand = new Random();
while (!answer.equalsIgnoreCase("done")) {
int idx = rand.nextInt(size - 1);
int sumab = divisible7List.get(idx);
int a = 1 + rand.nextInt(sumab);
int b = sumab - a;
sb.append(a);
sb.append(" + ");
sb.append(b);
sb.append(" = ");
sb.append(sumab);
System.out.println(sb.toString());
sb.setLength(0);
System.out.println("Do you want to continue?");
answer = scan.nextLine();
}
为了等待+ b适合您的需要,只需预先生成需要并找到a和b。