Click here to Skip to main content
15,885,029 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to make a program that well tell me what ever the user input is, it should tell me if it is either a palindrome or not. When user enters 0, I want it to exit out of the loop. Please help me do that! Thank you :D

What I have tried:

import java.util.Scanner;
class Palindrome
{
     public static void main(String args[])
     {
		 Scanner in = new Scanner(System.in);
		 
		 boolean isPalindrome = true;
		  
		  while (isPalindrome)
		  {
			  String reverseString="";
			  Scanner scanner = new Scanner(System.in);
			  
			  System.out.println("Enter a positive integer (0 to quit):");
			  String inputString = scanner.nextLine();
			  
			  int length = inputString.length();
			  
			  int i = length-1;
			  while ( i >= 0)
			  {
				  reverseString = reverseString + inputString.charAt(i);
				  i--;
			  }
			  
			  if (inputString.equals(reverseString))
			  System.out.println(inputString + " is a palindrome.");
			  else
			  System.out.println(inputString + " Input string is not a palindrome.");
			  
		  }
	  }
}
Posted
Updated 14-Oct-19 10:19am
Comments
Mohibur Rashid 14-Oct-19 16:21pm    
is
Madam a palindrome?
LillyLeaf 14-Oct-19 16:53pm    
yes
Mohibur Rashid 15-Oct-19 18:25pm    
In this case, you will have to handle case.

1 solution

Solution:

if(inputString.compareTo("0") == 0) 
  return;
// or
  break;


I know you are in the process of learning. Let me explain why the following is the worst way of writing java

BAD CODE
while ( i > 0) {
    reverseString = reverseString + inputString.charAt(i);
    i--;
}


Why?
By default java concat string using StringBuilder class(Except some literal value cases). so, if you write
String x = a + b;

Java will process this as
StringBuilder temp_var = new StringBuilder();
temp_var.add(a);
temp_var.add(b);
x = temp_var.toString();


This look clean on a string that is written outside of a loop. But what would happen when you use this inside a loop? It will create object for every operation.
 
Share this answer
 
v2
Comments
LillyLeaf 14-Oct-19 16:53pm    
Thank you for your amazing help! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900