问题描述
public static void test(int N) {
int enable_print = N % 10;
while (N > 0) {
if (enable_print == 0 && N % 10 != 0) {
enable_print = 1;
} else if (enable_print == 1) {
System.out.print(N % 10);
}
N = N / 10;
}
}
解决方法
有时重写而不是调试更容易和/或更好。
用伪代码编写或思考您的算法,然后将每个高级步骤分解为更多伪代码。您的条件看起来很奇怪,因此很难调试。
最好不要将打印直接嵌入循环的中心。相反,构建一个字符串并返回它。让调用者打印一个字符串。
System.out.println (reverseInt (12345));
public static String reverseInt (anInt) {
Initialize a StringBuffer with an empty string.
while (anInt > 0) {
Get last digit by modulo 10 and put in StringBuffer.
Prepend digit in StringBuffer.
Chop off last digit by doing integer divide.
}
return StringBuffer's .toString ();
}
另一种算法将递归调用 reverseInt 以构建不断增长的字符串。
,if 和 else if 都按照从上到下的顺序一起工作
if(true) { 执行 } else if() { 完成执行,即使条件为真 } else { 完成执行}
if(false) else if(check condition) { if true 否则执行下一个条件}
等等..
就您而言,这将是解决方案
public static void test(int N) {
int enable_print = N % 10;
while (N > 0) {
if (enable_print == 0 && N % 10 != 0) {
enable_print = 1;
}
if (enable_print == 1) {
System.out.print(N % 10);
}
N = N / 10;
}
}