Solution - 生成加法题目
Problem.
- Problem 1: 为幼儿园的小朋友生成
n
道1到100内的加法题目(两个数需要是随机正整数,且均小于100),n
由园长指定(键盘输入); - Problem 2: 在Problem 1的基础上,考虑小朋友没学过100以上的数,所以两个数的和不能大于等于100。Problem 1的程序需要如何改进才能满足这个需求?请提供新代码。
Solution.
GenerateAdditionProblems.java
import java.util.Random;
import java.util.Scanner;
public class GenerateAdditionProblems {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input number of problems to be generated: ");
int n = scanner.nextInt();
scanner.close();
generateAdditionProblems(n); // for problem 1
System.out.println("--------Sum no greater than 99-------");
generateAddProblems(n); // for problem 2
}
// for problem 1
static void generateAdditionProblems(int n) {
Random rand = new Random();
for (int i = 0; i < n; i++) {
int a = rand.nextInt(1, 100);
int b = rand.nextInt(1, 100);
System.out.printf("%2d + %2d = (%3d)\n", a, b, a + b); // %2d指占两个字符的位置,即使是一位数
}
}
// for problem 2
static void generateAddProblems(int n) {
Random rand = new Random();
int i = 0; // 记录已经生成的题目数
while (i < n) {
int a = rand.nextInt(1, 100);
int b = rand.nextInt(1, 100);
if (a + b < 100) {
System.out.printf("%2d + %2d = (%3d)\n", a, b, a + b); // %2d指占两个字符的位置,即使是一位数
i++;
}
}
}
}