试图比较两个整数
Trying to compare two ints
这是我第一次提问,我试着先搜索现有的讨论帖。我的程序旨在要求用户输入一个 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.");
}
}
}
将数字转换为数组并反转它而不是计算它更容易:
let reverseNumber = parseInt(12345.toString().split("").reverse().join());
看看你在做什么!
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;
}
这是我第一次提问,我试着先搜索现有的讨论帖。我的程序旨在要求用户输入一个 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.");
}
}
}
将数字转换为数组并反转它而不是计算它更容易:
let reverseNumber = parseInt(12345.toString().split("").reverse().join());
看看你在做什么!
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;
}