I am trying to write a Palindrome class using Stacks to determine if a word entered by user is a palindrome. There seems to be an issue in my Palindrome class. Can someone please help me identify it? My program works but no matter what word I type, it returns that the word is not a palindrome.
import java.util.Stack;
public class Palindrome
{
public Palindrome()
{
Stack stack = new Stack();
String input = "";
boolean isPalindrome = false;
for(int i = 0; i < input.length(); i++)
{
stack.push(i);
}
String opposite = " ";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
if(input.equals(opposite))
isPalindrome = true;
else
isPalindrome = false;
}//end main
}//end class Palindrome
Here is my PalindromeCheck class:
import java.util.Scanner;
public class PalinDromeCheck
{
public static void main(String[] args)
{
Palindrome pal = new Palindrome();
Scanner type = new Scanner(System.in); //create scanner for user to type a word
String word = null; //initial word to check
String stop = null; //stops processing of word
do
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(pal.equals(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
System.out.println("Would you like to try another word? Type Y for 'Yes' or N for 'No'");
stop = type.nextLine(); //stops processing
}
while(stop.equalsIgnoreCase("y")); //continues to process and ignores upper or lowercase Y
}
}
You have several bugs.
First, you need to give the input to the Palindrome class.
Second, when you reverse the input using stack, you push the index on the stack, not the character.
Third, it's not a good practice to do everything une constructor. Palindrome class doesn't need to know the input as member or for initialization purpose
If you don't need to have several implementation of Palindrome, you shall use a static method.
Try this :
public class Palindrome
{
public static boolean isPalindrome(String input)
{
char[] inputArray = input.toCharArray();
bool isOk = true;
for(int i = 0; i < inputArray.length/2 && isOk; i++){
isOk &= inputArray[i] == inputArray[inputArray.length - i - 1];
}
return isOk;
} // end method
} //end class Palindrome
Then, your main function could be :
public static void main(String[] args)
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(Palindrome.isPalindrome(word)) {
System.out.println("is a palindrome");
} else {
System.out.println("is not a palindrome\n");
}
} // End of main
Is this your full Palindrome-Class? If yes, it has no input to handle!
public class Palindrome
{
public static boolean isPalindrome(String input)
{
Stack stack = new Stack();
for(int i = 0; i < input.length(); i++)
{
stack.push(input.charAt(i));
}
String opposite = "";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
return input.equals(opposite);
}//end main
}//end class Palindrome
this creates a static method you can use in your code like:
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(Palindrome.isPalindrome(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
Your input is empty because you set input to "" in the constructor. You would be better off using a constructor argument to contain the input and then keep track of that using a member variable.
The code you typed is probably better suited to be in a method (equals perhaps? You will have to override this). You might want to consider pushing the character from the input string onto the stack rather then 0, 1, 2, 3... n (where n = input.length() - 1).
Your current .equals(word) does not do what you think it does because you have not provided an overload.
Related
I know it's very puny thing for experts here but I want to check why my palindrome program is not working as expected, it shows as palindrome to every number or string i enter, can you please look into it where the issue is, please.
actually i'm trying to create this program on my own and not checking any ready made method for it so asking here. please help.
here's my program
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length()/2;
boolean b = true;
while(s>0){
for (int i = 0; i<=s; i++) {
if(k.charAt(i)==k.charAt(s)){
b = true;
}
}
if (b)
s--;
else
System.out.println("exit");
}
if(b)
System.out.println("palindrome");
}
}
s is the midpoint, and you are modifying it in your loop. Also, you never set b to false in any condition. Fixing those two bugs, should give you something like
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length() / 2;
boolean b = true; // <-- Default to true
for (int i = 0; i <= s; i++) { // <-- Only need one loop.
if (k.charAt(i) != k.charAt(k.length() - i - 1)) {
b = false; // <-- Only need to update when it isn't a palindrome.
break; // <-- terminate the loop.
}
}
if (b) { // <-- Use braces. Even when optional.
System.out.println("palindrome");
}
You might be better off writing a simple method to do the check and call that method with your input.
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String str = sc.next();
System.out.printf("'%s' %s%n", str, (isPalindrome(str) ? "is " : "is not ") + "a palindrome.");
For inputs of radar and abcdcbc prints
'radar' is a palindrome.
'abcdcbc' is not a palindrome.
The method
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - i - 1)) {
return false; // return as soon as characters don't match
}
}
// if the program gets this far, the string must be a palindrome
return true;
}
Im stuck on this, I need a code that use 2 nested loops for this assignment (there are other solutions, but I need to demonstrate my understanding of nested loops). But I just dont get it. The outer loop repeats the entire algorithm and the inner loop iterates half-way (or less) through the string. I am not sure on what I need to put inside the for loops. This is what I have so far. Any Assistance would be pleasured.
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String x = 0;
String y = input.length-1;
for (String i = 0; i < line.length-1; i ++){
for (String j = 0; j < line.length-1; j ++){
if (input.charAt(x) == input.charAt(y))
{
x++;
y--;
}
}
}
}
Example Output:
Enter a string: 1331
1331 is a palindrome.
Enter a string: racecar
racecar is a palindrome.
Enter a string: blue
blue is NOT a palindrome.
Enter a string:
Empty line read - Goodbye!
Your algorithm is flawed, your nested loop should be to prompt for input - not to check if the input is a palindrome (that requires one loop itself). Also, x and y appear to be used as int(s) - but you've declared them as String (and you don't actually need them). First, a palindrome check should compare characters offset from the index at the beginning and end of an input up to half way (since the offsets then cross). Next, an infinite loop is easy to read, and easy to terminate given empty input. Something like,
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string: ");
System.out.flush();
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
boolean isPalindrome = true;
for (int i = 0; i * 2 < line.length(); i++) {
if (line.charAt(i) != line.charAt(line.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.printf("%s is a palindrome.%n", line);
} else {
System.out.printf("%s is NOT a palindrome.%n", line);
}
}
System.out.println("Empty line read - Goodbye!");
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String reversedText ="";
for(int i=line.length()-1/* takes index into account */;i>=0;i++) {
reversedText+=line.split("")[i]; //adds the character to reversedText
}
if(reversedText ==line){
//is a palidrome
}
}
Your code had lot of errors. I have corrected them and used a while loop to check if its a palindrome or not. Please refer below code,
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
String line;
boolean isPalindrome = true;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
int x = 0;
int y = line.length() - 1;
while (y > x) {
if (line.charAt(x++) != line.charAt(y--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(line + " is a palindrome");
} else {
System.out.println(line + "is NOT a palindrome");
}
System.out.println();
}
}
}
Question: Repeated Sequence Check
The program should enter a string (possibly containing blanks), and determine whether the characters are in
lexicographic order.
For example:
“12AABab” is in order since each character is less than or equal to the one following it (‘1’ < ‘2’, ‘2’ <
‘A’, ‘B’ < ‘a’, etc.) according to the Unicode character sequence.
“abCDef” is out of order, because ‘b’ > ‘C’ (lower-case letters come after upper-case letters in the
Unicode sequence).
If the string is in order, the program should display “The input is in order”; otherwise, it should display
“The input is out of order”
The program should repeat this process until the user enters the string “quit”, regardless of case. It should
not check the sequence of “quit”.
Finally, the program should display “Goodbye”.
Notes:
This program will require nested loops. The inner loop will check the sequence of the input, while
the outer loop will repeat the input and check process.
Be sure to reinitialize all variables at the start of the outer loop.
A string of length 0 or 1 is considered to be in order by definition.
what I could do best is: (I tried with 2 other different methods I could send it too if you like)
package homelab03;
import java.util.Scanner;
public class Quest3deneme3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String whole,remain,d,e;
char h1,h2;
int lenght,b,c,sayac;
//int[] a;
String[] a;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
whole=whole.replaceAll("\\s+","");
lenght=(int)whole.length();
//System.out.println(+lenght);
remain=whole;
sayac=0;
c=0;
b=0;
a= new String[lenght];
//boolean cem = d.compareTo(e);
while(b<lenght)
{
a[b]=remain.substring(b,b+1);
remain=remain.substring(b+1);
System.out.println(a[b]);
d=a[b];
e=a[c];
while(a[b]<a[c] )
{
sayac=sayac+1;
h1=h2;
}
}
if(sayac==lenght)
{
System.out.println("oley");
}
else
{
System.out.println("nooo");
}
}
//a[b]=remain.substring(b,b+1);
//remain=whole.substring(b+1);
//System.out.println(a[b]);
}
note we haven't learned a[b] <= this thing yet but I find it online if the solution won't require that that would be better.
note 2: we haven't learned regex either I think that might be dissalowed (I found some answers with that online but I think I won't get credit for that)
You could check this code. Maybe it will inspire you :)
import java.util.Scanner;
public class howToDoRepeatedSequanceCheck {
public void repeatedTests() {
String whole;
int inputLength,i;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
while(!whole.equals("quit")) {
whole=whole.replaceAll("\\s+","");
inputLength = whole.length();
boolean isInOrder = true;
i = 0;
while(isInOrder && i<inputLength-1 ) {
if(whole.charAt(i)<whole.charAt(i+1)) {
// System.out.println("ok " + whole.charAt(i)+ " < " +whole.charAt(i+1));
}else {
// System.out.println("error");
isInOrder = false;
}
i++;
}
if(isInOrder == true) {
System.out.println("The input is in order");
}else {
System.out.println("The input is out of order");
}
System.out.println();
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
}
System.out.println("Goodbye");
}
}
I am trying to make a java program to reverse the given string and each time iterate, compare with the reversed string then to print pass if matched else fail.
My program is:
package sss;
import java.util.Scanner;
public class ssi {
/**
* #param args
*/
public static void main(String[] args) {
String original,reverse="";
Scanner sc=new Scanner(System.in);
int ascii11,ascii12,ascii13,ascii14;
System.out.println("enter the string to be reversed");
original=sc.next();
int length=original.length();
for(int i=length-1;i>=0;i--)
{
reverse=reverse+original.charAt(i);
}
System.out.println(reverse);
//System.out.println(original);
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}
}
// TODO Auto-generated method stub
sc.close();
}
}
here each time when the for loop iterates i am getting pass or fail for each pair of numbers but i want the o/p as to print only pass or fail ONCE.
can any one help me out please...
Example Code:
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
String original;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string to be reversed: ");
original = sc.next();
int halfLength = original.length()/2;
int lastIndex = original.length() - 1;
int i;
for(i = 0; i < halfLength; i++) {
if(original.charAt(i) != original.charAt(lastIndex - i)) {
System.out.println("Fail!");
break;
}
}
// Managed to match all characters
if(i == halfLength) {
System.out.println("Pass!");
}
sc.close();
}
}
Input/Output:
Enter the string to be reversed: banana
Fail!
Enter the string to be reversed: RADAR
Pass!
Enter the string to be reversed: asdwwdsa
Pass!
So the idea is to:
Compare the first half of the string with the second half of the string
Compare the first character with the last character
Compare the 2nd character with the 2nd last character, and so on.
If any character does not match, print Fail!
If the loop finishes, it implies that the string is a palindrome (original == reversed), print Pass!
You need to flag each comparison of the original and reversed characters with either a pass or a fail boolean value. Obviously if any of them are flagged with a fail, you can then terminate the algorithm and print fail. If the for loop continues with a pass right to the end, then print pass once outside of the for loop.
Your print statement is inside the loop , so its printing "pass" or "fail" for each loop. You should use a flag to check whether all the ascii characters are same. and then check the status of flag outside the loop.
OR
Use StringBuffer it has a built-in method to reverse string.
StringBuffer input = new StringBuffer("Your String to reverse");
String reverse = input.reverse().toString();
if(input.equals(reverse))
System.out.println("pass");
else
System.out.println("fail");
Move your if condition out of for loop.
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
}
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}
I am writing a program that would help me find whether the number entered is a palindrome or not but i am trying it using arrays. And i would like to know if that is even possible?? And if it is possible then what am i doing wrong.
I have marked the code where i think the problem lies but feel free to suggest anything.!!!!
Thanks!!!
import java.util.Scanner;
public class palindrome
{
public static void main(String args[])
{
int size = 10,i,j,flag=0;
int num[] = new int[size];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the number ");
size = sc.nextInt();
System.out.println("Enter the number ");
for(i=0;i<size;i++)
{
num[i]=sc.nextInt();
}
i=size-1;
for(j=0;j<(size/2);j++,i--)
{
if(i>(size/2))
{
if(num[i]==num[j])
{
flag = 1;
}
}
}
if(flag==1)
{
System.out.println("The number is a palindrome");
}
else
System.out.println("The number is not a palindrome ");
}
}
Edit: Guys the problem is actually solved because i was doing a blunder mistake i.e. i was asking the user to enter the number in the form of an arry but i was not actually entering the digits in the number one by one instead i was entering the whole number in the first iteration.
But still a lot of thanks for the replies. I would still try your ideas and let you guys know. Thanks
:)
Try
public boolean isPalindrome(int[] num){
for(int i = 0 ; i < num.length/2 ; i++) {
if(num[i]!=num[num.length-(i+1)]) return false;
}
return true;
}
Yes it's possible, moreover, it's possible by using ArrayList, String - whatever you like. In order to write down a correct implementation, first decompose your current solution:
// Extract a method, do not cram all code into main()
// note: all you need is array, to get size of the array, put value.length
private static boolean isPalindrome(int[] value) {
...
}
public static void main(String args[]) {
int userInput[];
...
if (isPalindrome(userInput)) {
System.out.println("The number is a palindrome");
}
else {
System.out.println("The number is not a palindrome");
}
}
Now, let's implement isPalindrome():
private static boolean isPalindrome(int[] value) {
if (null == value)
return true; //TODO: or false, or throw exception
for (int i = 0; i < value.length / 2; ++i)
if (value[i] != value[value.length - 1 - i])
return false;
return true;
}
The easiest and most intuitive way (imo) to check for palindromes is through recursion. The idea is simple:
Is the first and last char the same?
YES Remove first and last char and check first and last char of the new String
NO There is no palindrome.
When the input is only 1 char then it's trivial.
Have a look at this code:
private void isPalindrome(String number){
if(number.length() == 1){
System.out.println("yes");
}else if(number.charAt(0) == number.charAt(number.length()-1)){
isPalindrome(number.substring(1, number.length()-1));
}else{
System.out.println("no");
}
}
Testing with:
isPalindrome(String.valueOf(232)) Returns "yes"
isPalindrome(String.valueOf(23)) Return "no"
Of course this also works with Arrays just as easily. Replace the parameter with an array and search through the indices the same way. When cutting down the array just create a new smaller array without first and last index of the previous array.
Your class has several issues:
First you're not checking if a number is a palindrome or not. Your algorithm is flawed
Second, you're asking to enter a size but in the end, the user inputs it but you don't use it yourself. Instead, you're using that introduced value in the number array.
Here's how you should do it.
public class Palindrome {
private static boolean isPalindrome(int[] array) {
for (int i = 0, j = array.length-1; i < j; i++, j--) {
if (array[i] != array[j]) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many numbers do you want to enter? ");
int size = scanner.nextInt();
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.printf("Enter number %s: ", i+1);
numbers[i] = scanner.nextInt();
}
if (isPalindrome(numbers)) {
System.out.println("The number is a palindrome");
} else {
System.out.println("The number is not a palindrome");
}
}
}