为什么我用于检查数字是否为回文的代码不起作用? [英] Why my code for checking if a number is a palindrom won't work?

查看:64
本文介绍了为什么我用于检查数字是否为回文的代码不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java代码在这里:

My Java 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");
            }
        }
    }
}

仅当输入的数字为零时,代码才会识别回文.我无法理解原因.

The code will only recognize a palindrome if the numbers entered are zeroes. I'm having trouble understanding why.

推荐答案

这是因为x的值最终被更改了.这不是程序末尾的原始数字. 因此,在x下方加上另一个变量,例如: int y = x; 最后,在使用"if"条件时,请使用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;

if(y == isPalindrome)添加这样的新变量.

if (y == isPalindrome) Add new variable like this.

这篇关于为什么我用于检查数字是否为回文的代码不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆