Palindrome tester - java

So I have the majority of the code written and it works. Except for the iterative method keeps showing that it is not a palindrome regardless of what is typed in. I am at a loss as to how to remedy it here is the code.
//David Crouse Assignment 2
import java.util.Scanner;
public class Assignment2 {
public static boolean loop = false;
//main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Palindrome Checker!");
do{
System.out.print("Enter a string to check if it is a palindrome. ");
System.out.print("Enter x to exit.");
String word = input.nextLine();
word = word.replaceAll("\\s","");
word = word.toLowerCase();
//Exit Program
if(word.equalsIgnoreCase("x")){
System.out.println("End of program. Good Bye!");
System.exit(0);
}
if(iterativePalindromeChecker(word)){
System.out.println("Iterative Result: Palindrome!");
}else{
System.out.println("Iterative Result: Not a palindrome");
}
if(recursivePalindromeChecker(word)){
System.out.println("Recursive Result: Palindrome!\n");
}else{
System.out.println("Recursive Result: Not a palindrome\n");
}
loop = true;
}while (loop == true);
}
//Iterative Method
public static boolean iterativePalindromeChecker(String str){
boolean result = false;
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
result = false;
}
return result;
}
//Recusive Methods
public static boolean recursivePalindromeChecker(String str){
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))
return recursivePalindromeChecker(str.substring(1,str.length()-1));
return false;
}
}

Your iterative method never sets result to be true. Here's a modified version:
public static boolean iterativePalindromeChecker(String str){
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
return false;
}
}
return true;
}

Your iterative method does not set result = true anywhere, so it really can't help it. Although I think the iterative method could be better overall. Take a close look at what is happening in the recursive one and see if you can implement some of it (like the guard conditions) more closely in the iterative method, and keep in mind that you are not limited to a single index value in a for loop either. e.g.:
public static boolean iterativePalindromeChecker(String str) {
for(int start = 0, end = str.length() - 1; start < end; start++, end--) {
if(str.charAt(start) != str.charAt(end)) {
return false;
}
}
return true;
}

I'm guessing someone once told you that a function should only have one return point, and trying to follow that led you to using a mutable result variable which screwed you here. Using break poses the same ostensible problem anyway. Save yourself the headache and just return as soon as you know the answer.
public static boolean iterativePalindromeChecker(String str) {
int begin = 0;
int end = str.length() - 1;
while (begin < end) {
if (str.charAt(begin) != str.charAt(end)) {
return false;
}
begin++;
end--;
}
return true;
}

Related

Trying to find palindrome number

I am trying to find palindrome no but every time it is showing false for every no even for 121
please Help....
public boolean isPalindrome(int x) {
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(x==rev){
return true;
}
else{
return false;
}
}
enter image description here
As an option, you may create something like this:
public boolean isPalindrome(int x) {
StringBuilder sb = new StringBuilder();
sb.append(x);
return sb.toString().equals(sb.reverse().toString());
}
Because after your while loop ends, x will be 0, you have to act on a copy instead
public boolean isPalindrome(int x) {
int num = x;
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(num==rev){
return true;
}
else{
return false;
}
}
All you need to do is build the new number as you reduce the original. Then compare the two.
for (int i : new int[]{121,12321, 123,34543,20012}) {
System.out.printf("%6d - %s%n", i, isPalindrome(i));
}
public static boolean isPalindrome(int numb) {
int n = 0;
for (int b = numb; b > 0;) {
n *= 10;
n += b%10;
b/=10;
}
return n == numb;
}
Prints
121 - true
12321 - true
123 - false
34543 - true
20012 - false
Hope this is useful:
public static boolean palindrome(int n) {
int nPalindrome = 0;
int nCopy = n;
while (n != 0) {
nPalindrome = nPalindrome *10 + n % 10;
n = n / 10;
}
if (nCopy == nPalindrom) {
return true;
} else {
return false;
}
}
You function can be as simple as below
public static void main(String args[]){
int r,sum=0;
int n=454;//It is the number variable to be checked for palindrome
if(isPalindrome(n)) {
System.out.println("palindrome number ");
} else {
System.out.println("not palindrome number ");
}
}
public boolean isPalindrome(int n) {
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
return n==sum;
}

Checking if string has only one character mismatch of palindrome in java

I have to write a boolean function that takes a string and check if a string is a palindrome or not in java.
Here is my code
static boolean isPalindrome(String input)
{
int i = 0;
last = input.length() - 1;
while (i < last) {
if (input.charAt(i) != input.charAt(last))
return false;
i++;
last--;
}
return true;
}
I want to add this part to my code but I got stuck on that if there is only one character mismatch I should consider it as valid palindrome.
Sample results:
“book” ​-> true
“refer” ​-> true
“” ​​-> true
Instead of immediately returning false when two characters are different, you keep a count of how many pairs of characters are different:
static boolean isPalindrome(String input)
{
int i = 0;
int last = input.length() - 1;
int differentCount = 0;
while (i < last) {
if (input.charAt(i) != input.charAt(last)) {
differentCount++;
// only return false if more than one character is different
if (differentCount > 1) {
return false;
}
}
i++;
last--;
}
return true;
}
Add a boolean flag that tracks whether you already found a mismatching pair of characters:
static boolean isPalindrome(String input)
{
boolean firstMismatch = true;
int i = 0;
last = input.length() - 1;
while (i < last) {
if (input.charAt(i) != input.charAt(last)) {
if (firstMismatch) {
firstMismatch = false;
} else {
return false;
}
}
i++;
last--;
}
return true;
}

Any assistance for specific method calling using Driver class? (Palindrome)

Alright, so Im new to using a driver to call methods, and so far this is what ive come up with:
public boolean isPalindrome(String s)
{
int begin = 0;
int end = s.length() - 1;
while (begin < end)
{
if (s.charAt(begin) != s.charAt(end))
{
return false;
}
begin++;
end--;
}
return true;
}
How do I get my driver to print out true when they detect the String "Racecar".
Referencing can be done like:
class Palindrome {
public static void main(String[] args) {
Palindrome test1 = new Palindrome();
String str = "Racecar";
System.out.println("result: " + test1.isPalindrome(str.toLowerCase()));
}
public boolean isPalindrome(String s)
{
int begin = 0;
int end = s.length() - 1;
while (begin < end)
{
if (s.charAt(begin) != s.charAt(end))
{
return false;
}
begin++;
end--;
}
return true;
}
}
Output:
result: true

Checking to see if a string is a palindrome or not

I am very close to finishing my one practice problem that deals with a palindrome and a string parameter and I am stuck with the main method to call the method. Every time I compile my code it compiles, but then when I go to input data, it keeps on running and does not give me a result. Can anyone aid in me in what I need to do to get it to return the result? The problem just asks to create a method that checks if it is a palindrome, my main method to test it is what is giving me trouble.
This is my code:
import java.util.*;
public class TestisPalindrome
{
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() -1;
while(left < right) {
if(str.charAt(left) != str.charAt(right)) {
return false;
}
}
left ++;
right --;
return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string to see if it is a palindrome or not: ");
String st1 = scan.nextLine();
System.out.println(isPalindrome(st1));
}
}
right & left increment should be in while loop
while(left < right)
{
if(str.charAt(left) != str.charAt(right))
{
return false;
}
left ++;
right --;
}
You've created an infinite loop. You have a while loop, but never change the conditions.
while(left < right)
{
if(str.charAt(left) != str.charAt(right))
{
return false;
}
}
Assuming left < right when you start, this will never change.
You have lines to increment left and right, but your code will never reach those lines, since it never gets out of the while loop.
You are overthinking this. Look at StringBuffer:
StringBuffer input = new StringBuffer(str);
return str.equals(input.reverse()).toString);
Please note that there is a performance impact of your implementation:
while(left < right) { //multiply inner operations by n/2
if(str.charAt(left) != str.charAt(right)) { //three operations
return false;
}
//This need to be inside your while loop
left ++; //one operation
right --; //one operation
}
This leads to an O(n) = (n * 5) / 2. On the other hand, if you simply reverse a string, it's only O(n) = n in the worst case. This is not a significant impact, but can add up depending on how you're accessing this.
You can also solve it like this:
public static boolean isPalindrome (String str){
String convertedStr = "";
for (int i = 0; i <str.length(); i++){
if (Character.isLetterOrDigit(str.charAt(i)))
convertedStr += Character.toLowerCase(str.charAt(i));
}
if (convertedStr.equals(reverseString(convertedStr)))
return true;
else
return false;
} //End of isPalindrome
Here is the code I used to determine whether a string is Palindrome String or not:
private static boolean isPalindromeString(String str){
if (str == null)
return false;
int len = str.length();
for (int i=0; i<len/2 ; i++){
if (str.charAt(i) != str.charAt(len - i - 1)){
return false;
}
}
return true;
}
I hope this can help you.

Testing parentheses in a equation using stack java

I'm writing a program that will take in an equation and check if all the parentheses line up and it will output if it is good or not.
For Ex: (3+4) is good
((3*8) is NOT Good
I'm not allowed to use java's built in push() pop() methods ext..
I have to make my own which I think I got....I think!
The problem I'm having is in the Test() method.
First I'm not sure how to write the while loop like:
while(there are still characters)
Anyway the output I'm getting is: stack is empty -1
Any help is appreciated. I'm one of the slower program learners and I couldn't be trying any harder. Thanks.
Here's what I got:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(char item) {
top++;
stack[top] = item;
}
public int pop() {
//x = stack[top];
//top = top - 1;
top--;
return stack[top];
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty" + top);
return true;
} else
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
//}
public boolean test(String p ){
boolean balanced = false;
balanced = false;
//while ( )
for(char i = '('; i < p.length(); i++ ){
push('(');
}
for (char j = ')'; j < p.length(); j++){
pop();
}
if (isStackEmpty()) {
balanced = true;
//return balanced;
}
return balanced;
}
public static void main(String[] args) {
Stacked stacks = new Stacked(100);
String y = new String("(((1+2)*3)");
stacks.test(y);
//System.out.println(stacks.test(y));
}
}
Now I'm getting somewhere. I need to be pointed in the right direction again. Thanks everyone this helped big time. I still have a lot more to do but this is good for now. Eventually I need to create a two more methods: one "infix to postfix" and the other "evaluating postfix" and at the end I'll need to read in answers from a text file instead of putting my own into the main method. Thanks again much appreciated.
Unless you need to actually evaluate the equation, a stack is too complicated a solution here. You simply need a counter:
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
//check if there are more closed than open
if (openParentheses < 0) {
return false;
}
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
If you absolutely must use stacks, use this:
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
push('x'); //doesn't matter what character you push on to the stack
} else if (p.charAt(i) == ')') {
pop();
}
//check if there are more closed than open
if (stackIsEmpty()) {
return false;
}
}
if (isStackEmpty()) {
return true;
} else {
return false;
}
I agree with Griff except that you should include another check if you didn't have more closed parentheses than open. (x*y))( is not a valid entry.
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
if(openParentheses<0)
return false;
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
You may be required to use a stack, but this could be done with a simple counter. This will show you a how to iterate over the characters of a String:
boolean test(String p) {
int balance = 0;
for (int idx = 0; idx < p.length(); ++idx) {
char ch = p.charAt(idx);
if (ch == '(')
++balance;
else if (ch == ')')
--balance;
if (balance < 0)
return false;
}
return balance == 0;
}
Of course, you could replace the increment and decrement with pushes and pops, respectively, on a stack.
For parsing you can use a for loop over the index and address the character of the string at the certain index.
But you actually do not need a stack, an integer variable openBraces is sufficient:
initialize with 0
for '(' you increment the variable one
for ')' you decrement the variable one
if openBraces is <0, you immediately give an error
if at the end openBraces is not equal to 0, you give an error.
Since you should do your homework yourself, I did not post source code, only explanations ;)
I think you just need this --
for ( int i = 0 ; i < p.length(); i++ ) {
char c = p.charAt(i);
if ( c == '(' )
push('(');
else if ( c == ')' ) {
if ( isStackEmpty() ) {
// Return error here because of unbalanced close paranthesis
}
pop();
}
else {
// do nothing
}
}
You CAN use a stack if you must, but considering how simplistic this is, you just need a counter that you increment and decrement and check for 0 at the end.
If you do use a counter, you should check after every decrement if the value is less than 0. If so, throw an error.
Edited based on Ryan/Dave Ball's comments.
It could be done like this:
String equation = "(2+3))";
Integer counter = 0;
//while(equation)
for(int i=0; i<equation.length();i++)
{
if(equation.charAt(i)=='(')
{
counter++;
}
else
if(equation.charAt(i)==')')
{
counter--;
}
}
if(counter == 0)
{
System.out.println("Is good!!!");
}
else
{
System.out.println("Not good!!!");
}
}

Categories