无法搞清楚为什么我的code,用于检查数量是palindrom将无法正常工作。咨询AP preciated [英] Having trouble figuring out why my code for checking if a number is a palindrom won't work. Advice appreciated
问题描述
我目前对Java,所以我通常的语言和编程的理解是升技弱。我的code是在这里:
I'm currently new to Java, so my understanding of the language and programming in general is abit weak. My code is here:
import java.util.Scanner;
public class task2 {
public static void main(String args[]) {
System.out.print("Input a 3 digit int");
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int isPalindrome = 0;
while (x != 0)
{
isPalindrome = isPalindrome*10 + x % 10;
x /= 10;
}
{
if (x == isPalindrome){
System.out.print ("Yes, this is a palindrome!");
}
else {
System.out.print("No, try again");
}}}}
在code只能识别回文如果输入的数字是零。我无法理解为什么。感谢您的咨询!
The code will only recognize a palindrome if the numbers entered are zeroes. I'm having trouble understanding why. Thank you for the advice!
推荐答案
这是因为x的值是得到改变finally.Which是不是在程序结束时,原来的号码。 所以要略低于x像另一个变量: INT Y = X; 并且,同时使用的如果条件中使用的y此值作比较,而不是使用X在末端。它将运行完美。
This is because the value of x is getting changed finally.Which is not the original number at the end of the program. SO take another variable just below x like: int y = x; And at the end while using "if" condition use this value of y for comparison rather than using x. It will run perfectly.
INT X = scan.nextInt();
int x = scan.nextInt();
INT Y = X;
int y=x;
如果(Y == isPalindrome)添加新的变量是这样的。
if (y == isPalindrome) Add new variable like this.
这篇关于无法搞清楚为什么我的code,用于检查数量是palindrom将无法正常工作。咨询AP preciated的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!