- 分享
- 0
- 人气
- 0
- 主题
- 6
- 帖子
- 2087
- UID
- 202699
- 积分
- 1943
- 阅读权限
- 19
- 注册时间
- 2009-2-24
- 最后登录
- 2018-11-23
- 在线时间
- 8302 小时
|
本帖最后由 htuomrev 于 2014-10-6 03:23 AM 编辑
你必须用一个array或者list来记录factor,我按照你的题目写了一个example。
我把各个步骤都分开,分成了几个method,
整个过程被拆解成:getFactors(int) -> sumOfFactors(list) -> printResult(int, int)
以下为code:- import java.util.*;
- public class Number {
- public static void main(String[] args) {
-
- // Fast Test (Delete it if u dont wan fast preview)
- for (int i=6;i<=100;i++) {
- List<Integer> factors = getFactors(i);
- printResult(sumOfFactors(factors), i);
- }
- System.out.println();
- // Fast Test End
-
- Scanner in = new Scanner(System.in);
- while (true) {
- System.out.println("Enter a number,x which 6 <= x <= 1000");
- try {
- int input = in.nextInt();
- if (inputError(input)) {
- System.out.println("Input Range Error!");
- System.out.println();
- continue;
- }
- List<Integer> factors = getFactors(input);
- printFactors(factors);
- int sum = sumOfFactors(factors);
- printResult(sum, input);
- System.out.println();
- } catch (InputMismatchException e) {
- in.next(); // prevent repeat reading
- System.out.println("Input Type Error!");
- System.out.println();
- continue;
- }
- }
- }
-
- private static boolean inputError(int input) {
- if (input < 6 || input > 1000) return true;
- return false;
- }
-
- private static List<Integer> getFactors(int n) {
- List<Integer> factors = new ArrayList<Integer>(0);
- factors.add(1);
- factors.add(n);
- for (int i=2;i<n/2;i++) {
- if (n % i == 0) {
- if (factors.indexOf(i) < 0)
- factors.add(i);
- if (factors.indexOf(n/i) < 0)
- factors.add(n/i);
- }
- }
- return factors;
- }
-
- private static void printFactors(List<Integer> factors) {
- System.out.print("Factors: ");
- for (Integer factor : factors) {
- System.out.print(factor + " ");
- }
- System.out.println("");
- }
-
- private static int sumOfFactors(List<Integer> factors) {
- int sum = 0;
- for (Integer factor : factors)
- sum += factor;
- return sum;
- }
-
- private static void printResult(int sum, int input) {
- if (sum - input == input) {
- System.out.printf("%4d is Perfect Number!\n", input);
- } else if (sum - input > input) {
- System.out.printf("%4d is Excessive Number!\n", input);
- } else {
- System.out.printf("%4d is Defective Number!\n", input);
- }
- }
- }
复制代码 |
|