gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:42:50 24 4
gpt4 key购买 nike

最近,我找到了/ 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的基本概念...

最佳答案

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

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


如果要打印结果:

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


这样,Java不会将引用分配给变量( nx),但除此之外,它会做完全相同的事情。

关于java -/r/dailyprogrammer#218-如何正确使对象正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31103286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com