这是我第一次问一个问题,我曾试图先搜索现有的线程。我的计划是为了要求用户输入5位数字,它会检查,看它是否是一个回文通过反转数,然后原来的号码比较相反。我也摆在那里的一些验证步骤拒收号码,如果是长于或短于5位。一切似乎工作,直到它到达比较原始号码和扭转数的部分。这里是我的代码:
import java.util.Scanner;
public class Palindromes {
public static void main(String args[]) {
int n, reverse = 0;
System.out.println("Enter a 5-digit integer to see if it is a palindrome.");
Scanner in = new Scanner(System.in);
n = in.nextInt();
int length = String.valueOf(n).length();
while (length > 5 || length < 5) {
System.out.println("Error: integer must be 5 digits in length.");
System.out.println("Enter a 5-digit integer.");
n = in.nextInt();
length = String.valueOf(n).length();
}
while (length == 5 && n != 0) {
reverse = reverse * 10;
reverse = reverse + n % 10;
n = n / 10;
}
System.out.println("Reversed number is: " + reverse);
if (n == reverse) {
System.out.println("Congratulations! Your number is a palindrome!");
} else {
System.out.println("Sorry. Your number isn't a palindrome.");
}
}
}
看看你在这里做什么!
while (length == 5 && n != 0) {
reverse = reverse * 10;
reverse = reverse + n % 10;
n = n / 10; // <----- You are changing "n"!
}
这意味着,在循环后,n
将不再是用户输入的相同n
。
为了解决这个问题,n
复制到另一个变量和修改来代替。
int temp = n;
while (length == 5 && temp != 0) {
reverse = reverse * 10;
reverse = reverse + temp % 10;
temp = temp / 10;
}
它更容易地将数字转换为一个数组和反向它,而不是计算它的:
let reverseNumber = parseInt(12345.toString().split("").reverse().join());