为什么这段代码拒绝检查(12,13)?



我正在处理一个Java挑战,计算两个不同数字中的所有数字,如果任何两个数字相等,则返回true。代码工作得非常好,除了当它试图计算(12,13)时,由于某种原因,它甚至没有测试参数,它只是立即返回false。

我已经通过可视化器运行代码来查看每一步,并且似乎没有任何解释为什么它返回false。消息的输出也很好,所以方法调用没有问题。我是不是做错了什么我看不见的事?

public class Main {
public static void main(String[] args) {
System.out.println(hasSharedDigit(12, 23) + " should return true");
System.out.println(hasSharedDigit(9, 99) + " should return false");
System.out.println(hasSharedDigit(15, 55) + " should return true");
System.out.println(hasSharedDigit(12, 43) + " should return false");
System.out.println(hasSharedDigit(15, 76) + " should return false");
System.out.println(hasSharedDigit(12, 13) + " should return true");
}
public static boolean hasSharedDigit(int first, int second) {
if ((first >= 10 && first <= 99) && (second >= 10 && second <= 99)) {
int firstDigits = 0;
int secondDigits = 0;
while (first != 0) {
firstDigits = first % 10;
first = first / 10;
while (second != 0) {
secondDigits = second % 10;
second = second / 10;
if (firstDigits == secondDigits) {
return true;
}
}
}
}
return false;
}

}

这是因为

if (firstDigits == secondDigits) {
return true;
}

下面
while (second != 0)

if (firstDigits == secondDigits) {
return true;
}

在while循环之后因为在第12,13种情况下你得到

second = 0

然后是第一个&第二个数字不会被检查。

//试试这个就行了

public static boolean hasSharedDigit(int first, int second) {
if ((first >= 10 && first <= 99) && (second >= 10 && second <= 99)) {
int firstDigits = 0;
int secondDigits = 0;
while (first != 0) {
firstDigits = first % 10;
first = first / 10;
while (second != 0) {
secondDigits = second % 10;
second = second / 10;
}
if (firstDigits == secondDigits) {
return true;
}
}
}
return false;
}

}

相关内容

最新更新