Reputation: 159
import java.util.*;
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
System.out.print("Input a prefer number :");
int num=input.nextInt();
int reverse=0;
while(num!=0){
int num1=num%10;
reverse=(reverse*10)+num1;
num/=10;
}
System.out.println("Reverse num is "+reverse);
if(num==reverse){
System.out.println("The number is palindrome");
}else{
System.out.println("Try again");
}
}
}
I want to confirm whether it is a palindrome number or not when I input a number by the keyboard.But I couldn't get it.In the 7th line of my code,I've initialized variable "reverse" as 0.So when I make a condition in 14th line,"reverse" acts as 0.That is what should be,but i want to make "reverse" equal to the value which gets in line 10.What should I do ?
Upvotes: 0
Views: 91
Reputation: 40034
You might consider treating the number as a string.
Scanner input=new Scanner(System.in);
System.out.print("Input a preferred number :");
String str = input.nextLine();
StringBuilder sb = new StringBuilder(str);
String reverse = sb.reverse().toString();
System.out.println("Reverse num is "+reverse);
if(str.equals(reverse)){
System.out.println("The number is palindrome");
}else{
System.out.println("Try again");
}
}
Upvotes: 0
Reputation: 496
Assign num to another variable as its get changed
import java.util.*;
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
System.out.print("Input a prefer number :");
int num=input.nextInt();
int number = num ; // assign to anaother variable as num gets changed
int reverse=0;
while(num!=0){
int num1=num%10;
reverse=(reverse*10)+num1;
num/=10;
}
System.out.println("Reverse num is "+reverse);
if(number==reverse){
System.out.println("The number is palindrome");
}else{
System.out.println("Try again");
}
}
}
Upvotes: 2