/ r / dailyprogrammer#218 - 如何正确地使对象工作?

时间:2015-06-28 18:29:10

标签: java oop

最近我找到了/ r / dailyprogrammer,我做了其中一个挑战: https://www.reddit.com/r/dailyprogrammer/comments/38yy9s/20150608_challenge_218_easy_making_numbers/

使数字回文很简单,但毕竟Java是一种面向对象的语言,所以我决定使用对象。这是我到目前为止所得到的:

import java.math.*;

public class Lychrel {
    BigInteger in;
    BigInteger out;
    int steps;
    boolean isLychrel;

    public String get(BigInteger n) {
        Lychrel L = make(n);
        String S;
        if (L.isLychrel) {
            return "NUMBER " + L.in + " IS A LYCHREL NUMBER!";
        }
        if (L.steps == 0) {
            return "NUMBER " + L.in + " IS ALREADY PALINDROMIC! (NO STEPS NEEDED)";
        }
        if (L.steps == 1) {
            S = "STEP";
        } else {
            S = "STEPS";
        }
        return "NUMBER " + L.in + " GETS PALINDROMIC IN " + L.steps + " " + S + " (" + L.out + ")";
    }

    private static String palindrome(String str) {
        return new StringBuilder(str).reverse().toString();
    }

    private static boolean isPalindrome(String x) {
        return x.equals(palindrome(x));
    }

    private static Lychrel make(BigInteger n) {
        Lychrel lychrel = new Lychrel();
        BigInteger input = n;
        lychrel.in = input;
        final int MAX_STEPS = 100;
        for (int steps = 0; ; steps++) {
            String N = String.valueOf(n);
            if (isPalindrome(N)) {
                lychrel.steps = steps;
                lychrel.isLychrel = false;
                lychrel.out = new BigInteger(N);
                break;
            }
            String N_reversed = palindrome(N);
            n = n.add(new BigInteger(N_reversed));
            if (steps > MAX_STEPS) {
                lychrel.steps = 0;
                lychrel.isLychrel = true;
                lychrel.out = input;
                break;
            }
        }
        return lychrel;
    }
}

class Main {
    public static void main(String args[]) {
        Lychrel x = new Lychrel();
        System.out.println(x.get(new BigInteger("179")));
    }
}

它工作得非常好,但是我对创建实际的Lychrel对象感到有些困惑。是否可以这样做:

BigInteger n = new BigInteger("120");
Lychrel x = new Lychrel(n);
System.out.println(x);

而不是上面的内容? :

BigInteger n = new BigInteger("120");
Lychrel x = new Lychrel();
System.out.println(x.get(n));

在我看来,我还没有掌握OOP的基本概念......

1 个答案:

答案 0 :(得分:0)

使用新实例调用新对象方法的最简单方法是:

Lychrel x = new Lychrel().get(new BigInteger("120"));

如果你想打印结果:

System.out.println(new Lychrel().get(new BigInteger("120")));

这样,Java就不会为变量(nx)分配引用,但除此之外它就完全相同。