简体   繁体   中英

How to use the variable "rev" outside the while loop?

After running the code shown below, I receive the following error:

rev cannot be resolved to a variable

I have tried to declare the variable outside the while loop, but it only leads to more errors. Here is the code:

import java.util.Scanner;

public class PalindromeProject {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner num = new Scanner(System.in);
        System.out.println("Enter number to check if palindrome");
        int number = num.nextInt();
        int temp=number;
        while(temp!=0) {
         int rem=temp%10;
         int rev=(rev*10)+rem;
            temp=temp/10;
        }
        if(rev==number){
            System.out.println("Number provided is palindrome");
        }else {
            System.out.println("Number provided is not palindrome");
        }
    }
}

The reason the rev cannot be resolved to a variable is because you are performing operations with it outside of its scope.

You created the integer rev in the while loop. In this case, you can only make modifications in the loop.

If you want to perform operations on rev , you have to initialize it outside of the loop.

It should look like the following:

import java.util.Scanner;

public class PalindromeProject {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner num = new Scanner(System.in);
        System.out.println("Enter number to check if palindrome");
        int number = num.nextInt();
        int temp=number;
        int rev=0;
        while(temp!=0) {
         int rem=temp%10;
         rev=(rev*10)+rem;
            temp=temp/10;
        }
        if(rev==number){
            System.out.println("Number provided is palindrome");
        }else {
            System.out.println("Number provided is not palindrome");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM