[英]How do I distribute the remainder in groups?
嘿,我是编程新手,想知道如何使用 if 语句和模块编写这段代码。 我知道如何做第一部分,但我仍然坚持如何将其余学生分配到小组的 rest 中。 到目前为止,我的程序在下面:
package grouping.problem;
import java.util.Scanner;
public class GroupingProblem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of students: ");
int students = sc.nextInt();
System.out.println("Enter the number of groups: ");
int groups = sc.nextInt();
int groupsmade;
int randomgroups;
int studentin = 0;
int remainder;
if (students<=0 || groups<=0){
System.out.println("Invalid Input");
System.exit(0);
}
if (students%groups == 0){
studentin = students/groups;
groupsmade = students/studentin;
System.out.println("There are " + groupsmade + " groups of " + studentin + " students each");
}else if (students % groups != 0){
remainder = (students % groups);
System.out.println("Not an even amount of students");
}
} }
students % groups
的值是有多少组会有一个额外的学生:
import java.util.Scanner;
public class GroupingProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input number of students: ");
int students = scanner.nextInt();
System.out.print("Input number of groups: ");
int groups = scanner.nextInt();
if (students <= 0 || groups <= 0) {
System.out.println("Invalid Input");
System.exit(1);
}
int studentsLeftAfterEvenDistribution = students % groups;
int baseGroupSize = students / groups;
int groupsWithBaseGroupSize = groups - studentsLeftAfterEvenDistribution;
System.out.printf("There %s %d group%s of %d student%s each.%n",
areOrIs(groupsWithBaseGroupSize), groupsWithBaseGroupSize,
possiblyAddStoPluralize(groupsWithBaseGroupSize), baseGroupSize,
possiblyAddStoPluralize(baseGroupSize));
if (studentsLeftAfterEvenDistribution != 0) {
System.out.printf("There %s %d group%s of %d student%s each.%n",
areOrIs(studentsLeftAfterEvenDistribution), studentsLeftAfterEvenDistribution,
possiblyAddStoPluralize(studentsLeftAfterEvenDistribution), baseGroupSize + 1,
possiblyAddStoPluralize(baseGroupSize + 1));
}
}
private static String areOrIs(int groups) {
return groups != 1 ? "are" : "is";
}
private static String possiblyAddStoPluralize(int num) {
return num != 1 ? "s" : "";
}
}
用法示例 1:
Input number of students: 20
Input number of groups: 4
There are 4 groups of 5 students each.
用法示例 2:
Input number of students: 22
Input number of groups: 5
There are 3 groups of 4 students each.
There are 2 groups of 5 students each.
用法示例 3:
Input number of students: 3
Input number of groups: 5
There are 2 groups of 0 students each.
There are 3 groups of 1 student each.
用法示例 4:
Input number of students: 0
Input number of groups: 10
Invalid Input
用法示例 5:
Input number of students: 5
Input number of groups: 4
There are 3 groups of 1 student each.
There is 1 group of 2 students each.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.