Java 代码实现将数字分成三组
下面是一个 Java 代码的例子,实现了将给定的数字 n 分成 3 组的功能:
public class DivideIntoThreeGroups {
public static void main(String[] args) {
int n = 10;
divideIntoThreeGroups(n);
}
public static void divideIntoThreeGroups(int n) {
if (n < 3) {
System.out.println('n必须大于等于3');
return;
}
int groupSize = n / 3;
int remainder = n % 3;
int[] group1 = new int[groupSize + remainder];
int[] group2 = new int[groupSize];
int[] group3 = new int[groupSize];
// 给第一组分配数字
for (int i = 0; i < group1.length; i++) {
group1[i] = i + 1;
}
// 给第二组分配数字
for (int i = 0; i < group2.length; i++) {
group2[i] = group1.length + i + 1;
}
// 给第三组分配数字
for (int i = 0; i < group3.length; i++) {
group3[i] = group1.length + group2.length + i + 1;
}
System.out.println('第一组的数字:');
for (int num : group1) {
System.out.print(num + ' ');
}
System.out.println();
System.out.println('第二组的数字:');
for (int num : group2) {
System.out.print(num + ' ');
}
System.out.println();
System.out.println('第三组的数字:');
for (int num : group3) {
System.out.print(num + ' ');
}
System.out.println();
}
}
在上面的例子中,我们定义了一个名为 divideIntoThreeGroups 的方法,它接收一个整数参数 n。首先,我们检查 n 是否小于 3,如果是,则输出错误信息并返回。然后,我们计算每组的大小和余数。接下来,我们创建了三个整数数组 group1、group2 和 group3,分别用来存储每个组的数字。
然后,我们使用循环为每个组分配数字。首先,我们为第一组分配数字 1 到 group1.length,然后为第二组分配数字 group1.length+1 到 group1.length+group2.length,最后为第三组分配数字 group1.length+group2.length+1 到 group1.length+group2.length+group3.length。
最后,我们使用循环输出每个组的数字。
原文地址: https://www.cveoy.top/t/topic/pga0 著作权归作者所有。请勿转载和采集!