Problem with infinitely looping text in a word generator - java

I'm making a Palindrome Generator. Basically the user inputs a word or sentence and the program outputs whether or not its a Palindrome, which is a word that is spelled the same forwards and backwards like "wow" or "racecar". My program works fine, however the output text will repeat itself like fifty times and I can't seem to figure out where the issue is without messing everything up. Help would be appreciated.
import javax.swing.JOptionPane;
public class palindromedectector {
public static void main(String[] args) {
String testStrings = "";
testStrings = JOptionPane.showInputDialog("Enter word: ");
for (int i = 0; i < testStrings.length(); i++)
{
System.out.print("\"" + testStrings + "\"");
if (isPalindrome(stripString(testStrings)))
System.out.println(" is a palindrome.");
else
System.out.println(" is not a palindrome.");
}
}
public static String stripString(String strip)
{
strip = strip.toUpperCase();
String stripped= "";
for (int i= 0; i< strip.length(); i++)
{
if (Character.isLetter(strip.charAt(i)))
stripped += strip.charAt(i);
}
return stripped;
}
public static boolean isPalindrome (String str)
{
boolean status = false;
if (str.length() <= 1)
status = true;
else if (str.charAt(0) == str.charAt(str.length()-1))
{
status = isPalindrome (str.substring(1, str.length()-1));
}
return status;
}
}

Main issue is that you run isPalindrome check for the same string in the loop, probably you wanted to run multiple checks
public static void main(String[] args) {
final int attempts = 5;
for (int i = 0; i < attempts; i++) {
String word = JOptionPane.showInputDialog("Enter word: ");
System.out.print("\"" + word + "\"");
if (isPalindrome(stripString(word))) {
System.out.println(" is a palindrome.");
} else {
System.out.println(" is not a palindrome.");
}
}
}
Also, the main functionality may be implemented in a shorter way:
// use regexp to get rid of non-letters
private static String stripString(String word) {
if (null == word || word.isEmpty()) {
return word;
}
return word.replaceAll("[^A-Za-z]", "").toUpperCase(); // remove all non-letters
}
// use Java Stream API to check letters using half of word length
private static boolean isPalindrome(String word) {
if (null == word) {
return false;
}
final int len = word.length();
if (len < 2) {
return true;
}
return IntStream.range(0, len/2)
.allMatch(i -> word.charAt(i) == word.charAt(len - 1 - i));
}

Basic problem: You are testing if the word is a palindrome testStrings.length() times, ie once for every letter in the word, rather than just once.
Remove the for loop in your main() method.

Related

How could I get my program to check if a word is a palindrome irrespective of the case entered by the user

import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
isPailindrome(ori);
if (isPailindrome(ori))
System.out.println(ori + "is a Pailindrome");
else
System.out.println(ori + "is NOT a Pailindrome");
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
The code works perfectly I'm just confused how I will get it to work irrespective of the case
inputted by the user. For example aBba is a palindrome but It says it's not in the code I've done. I
would like any help if possible thanks.
You can convert all of the letters to lowerCase before you start the processing.
You can write your own function or use toLowerCase() String function.
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
ori = ori.toLowerCase();
isPailindrome(ori);
if (isPailindrome(ori))
}
System.out.println(ori + "is a Pailindrome");
} else {
System.out.println(ori + "is NOT a Pailindrome");
}
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
Take the input and call toUpper(); that way when you check to see if it is a palindrome, all of the characters are uppercase.
String ori = scr.nextLint();
if(isPalindrome(ori.toUpperCase()))
//do something
Convert all the cases to lowercase/uppercase before checking the palindrome
isPailindrome(ori.toLowerCase());
Zoom in from both ends and adjust the case as required.
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len >>1; i++) {
if (Character.toLowerCase(str.charAt(i)) !=
Character.toLowerCase(str.charAt(len - i - 1))) {
return false;
}
}
return true;
}

pig latin-like program - issues with vowels

I'm writing a program that has two rules:
1. If the first character of the word is a vowel, then move it to the end of the word.
2. If the first character of the word is a consonant, then move it to the end of the word and append 'ae'.
import java.util.Scanner;
public class Program5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String english = scanner.nextLine();
String piggy = piggyEnglish(english);
System.out.print("Translated: " + piggy);
}
private static String piggyEnglish(String s) {
String piggy = "";
int i = 0;
while (i<s.length()) {
while (i<s.length() && !isLetter(s.charAt(i))) {
piggy = piggy + s.charAt(i);
i++;
}
if (i>=s.length()) break;
int begin = i;
while (i<s.length() && isLetter(s.charAt(i))) {
i++;
}
int end = i;
piggy = piggy + piggyWord(s.substring(begin, end));
}
return piggy;
}
private static boolean beginsWithVowel(String word){
String vowels = "aeiou";
char letter = word.charAt(0);
return (vowels.indexOf(letter) != -1);
}
private static boolean isLetter(char c) {
return ( (c >='A' && c <='Z') || (c >='a' && c <='z') );
}
private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split) + word.substring(0, split);
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}
private static int firstVowel(String word) {
word = word.toLowerCase();
for (int i=0; i<word.length(); i++)
if (word.charAt(i)=='a' || word.charAt(i)=='e' ||
word.charAt(i)=='i' || word.charAt(i)=='o' ||
word.charAt(i)=='u')
return i;
return 0;
}
}
The following is the expected output:
Please enter a sentence: today is a beautiful day
Translated: odaytae si a eautifulbae aydae
However, this is what I'm getting:
Please enter a sentence: today is a beautiful day
Translated: odaytae is a eautifulbae aydae
Basically, it doesn't translate any words that start with a vowel. I think the problem stems from the piggyWord method, but I'm not certain. Can I get any pointers on how to fix this?
The error lies in the piggyWord function:
private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split + 1) + word.substring(0, split + 1); //Since vowel is in 1st place, substring(0,0) returns empty string.
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}
Based on your rules, you don't need the method firstVowel() to get the index of the first vow in a word because you only need to know whether the first character in the word is a vow or not.
So simply change you piggyWord method to the following will solve your problem:
private static String piggyWord(String word) {
if(beginsWithVowel(word)) {
return word.substring(1) + word.substring(0, 1);
} else {
return word.substring(1) + word.substring(0, 1)+"ae";
}
}
Or more simply:
private static String piggyWord(String word) {
String result = word.substring(1) + word.substring(0, 1);
return beginsWithVowel(word) ? result : result + "ae";
}
Because you always have to move the first character of a word to the end, the only thing is that whether you need to append an extra "ae" in the end or not.
If only the first letter is concerned than in "firstVowel" you can return 1 if vowel is at first position.
private static int firstVowel(String word) {
word = word.toLowerCase();
for (int i=0; i<word.length(); i++)
if (word.charAt(i)=='a' || word.charAt(i)=='e' ||
word.charAt(i)=='i' || word.charAt(i)=='o' ||
word.charAt(i)=='u')
return 1;
return 0;
}

Palindrome ignoring spaces and punctuation

public static void main(String[] args)
{
Scanner sentence = new Scanner(System.in);
System.out.println("This program will determine if an inputted phrase is a palindrome.");
System.out.println(" ");
System.out.println("Enter a phrase, word, or sentence:");
String a = sentence.nextLine();
String b = a.toLowerCase().replaceAll("[^a-z]"," "); //as long as the words are spelt the same way, the caps don't matter and it ignores spaces and punctuation
System.out.println();
System.out.println(palindromeChecker(b)); //calls method
}
public static String palindromeChecker(String b)
{
String reverse = new StringBuilder(b).reverse().toString();
String c;
if(b.equals(reverse)) {
c = "The word " +b+ " is a palindrome"; }
else {
c = "The word " +b+ " is not a palindrome"; }
return c;
}
}
My, problem is that for example, if i do Eva, can I see bees in a cave? It should be a palindrome, however it's not can u please help me with this and please try not to make it complicated.
Replace:
String b = a.toLowerCase().replaceAll("[^a-z]"," ");
With
String b = a.toLowerCase().replaceAll("[^a-z]","");
Otherwise, you're replacing non-alphabetical characters with spaces, which can influence the checking of the reverse String.
You need to remove all non-letters from your string:
public class Palindrome {
public static String strip(String s) {
return s.toLowerCase().replaceAll("[^a-z]", "");
}
public static boolean isPalindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(strip("Eva, can I see bees in a cave?"));
System.out.println(isPalindrome(strip("Eva, can I see bees in a cave?")));
}
}
Output:
evacaniseebeesinacave
true
public class PalindromeStringWithReverse {
public static void main(String[] args) {
String str = "21raceca r12";
str = str.replaceAll(" ", "");
boolean isPalindrome = false;
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) == str.charAt((str.length() - 1) - i)) {
isPalindrome = true;
continue;
}
isPalindrome = false;
}
if (isPalindrome) {
System.out.println("Palindrome");
} else {
System.out.println("not palindrome");
}
}
}

Why is my code only outputing that the string is balanced

I need the following code to have a default constructor of BalancedString that initializes str to the empty string and resets a counter to 0 The class's one arguement constructor passes a string s to str and resets counter to zero. The BalancedString class also provides a boolean method which is boolean balanced() that returns true if a string contains a balanced amount of parenthesis
import java.util.*;
public class BalancedString {
private static String str;
public BalancedString()
{
str = "";
}
public BalancedString(String s)
{
s = "";
str = s;
}
public boolean balanced(){
return true;
}
public static void main(String[] args) {
int n = 0;
CounterFancy.setCounter(n);
Scanner input = new Scanner(System.in);
System.out.println("Enter a string that has any number of Left and right Parenthesis");
String s = input.next();
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
int counterValue = CounterFancy.getCounter();
if (counterValue == 0)
System.out.println("The string is Balanced");
else
System.out.println("The string is NOT Balanced");
input.close();
}
public String getStr()
{
return str;
}
public String setStr(String s)
{
str = s;
return str;
}
}
AND the following is the other project that i got the CounterFancy classes from, but the problem is above^^ why is this only outputing that it is balanced
//Joe D'Angelo
//CSC 131-03
//Chapter 10 Programming Assignment 5a.
//Takes the user's input of whether they want the counter to be negative or positive and outputs
//10 values of the user's selected input, then restarts the counter at 0
import java.util.*;
public class CounterFancy { //I messed up the first time and had to change FancyCounter to CounterFancy that is why this is changed
private static int counter;
public CounterFancy()
{
counter = 0;
}
public CounterFancy(int n){
counter = n;
}
public static int incCounter() //inc stands for increment
{
counter++;
return counter;
}
public static int decCounter() //dec stands for decrement
{
counter--;
return counter;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Press 1 for Possitive or Press 2 for Negative");
int reply = input.nextInt();
if (reply == 1)
{
for (int i = 1; i <=10; i ++)
System.out.println("counter: " + CounterFancy.incCounter());
CounterFancy.setCounter(5);
System.out.println("Counter: " + CounterFancy.getCounter());
}
if (reply == 2)
{
for (int i = 1; i <=10; i ++)
System.out.println("counter: " + CounterFancy.decCounter());
CounterFancy.setCounter(5);
System.out.println("Counter: " + CounterFancy.getCounter());
}
input.close();
}
public static int getCounter()
{
return counter;
}
public static void setCounter(int n)
{
counter = 0;
}
}
You are making a couple of mistakes in your BalancedString class definition. First, the str field should not be static. By making it static, all instances share the same str field.
Second, and perhaps more critical, you are not constructing your BalancedString properly. You are setting the argument back to the empty string every time!
public BalancedString(String s) {
s = ""; // THIS LINE SHOULD NOT BE HERE!
str = s;
}
Finally, your balanced() method is simply returning true regardless of the string. You need to implement some logic here.
Regarding the main program: you need to loop through all the characters, increment for each '(' and decrement for each ')' character. Instead of this:
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
You should have a loop like this:
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '(')
CounterFancy.incCounter();
else if (c == ')')
CounterFancy.decCounter();
}
There's a logic problem in this bit of code:
String s = input.next();
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
int counterValue = CounterFancy.getCounter();
if (counterValue == 0)
System.out.println("The string is Balanced");
else
System.out.println("The string is NOT Balanced");
You're only searching the string once for a ( and once for a ). If the string contains both a ( and a ) in any order, the counter will always count 1, then 0, and think that the parentheses are balanced.
You need to put the counting in a loop to check whether or not the parentheses are balanced. You should loop through each of the characters and check the count at each step. The parentheses are balanced if the count is non-negative at each step and ends at 0.

Java way to check if a string is palindrome [duplicate]

This question already has answers here:
Check string for palindrome
(42 answers)
Closed 7 years ago.
I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations
Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.
The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.
boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
For the least lines of code and the simplest case
if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
Here is a simple one"
public class Palindrome {
public static void main(String [] args){
Palindrome pn = new Palindrome();
if(pn.isPalindrome("ABBA")){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
public boolean isPalindrome(String original){
int i = original.length()-1;
int j=0;
while(i > j) {
if(original.charAt(i) != original.charAt(j)) {
return false;
}
i--;
j++;
}
return true;
}
}
You can try something like this :
String variable = ""; #write a string name
StringBuffer rev = new StringBuffer(variable).reverse();
String strRev = rev.toString();
if(variable.equalsIgnoreCase(strRev)) # Check the condition
Here's a good class :
public class Palindrome {
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
protected static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i--) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c)) {
dest.append(c);
}
}
return dest.toString();
}
protected static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
String string = "Madam, I'm Adam.";
System.out.println();
System.out.println("Testing whether the following "
+ "string is a palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(string)) {
System.out.println("It IS a palindrome!");
} else {
System.out.println("It is NOT a palindrome!");
}
System.out.println();
}
}
Enjoy.
public boolean isPalindrom(String text) {
StringBuffer stringBuffer = new StringBuffer(text);
return stringBuffer.reverse().toString().equals(text);
}
I guess this is simple way to check palindrome
String strToRevrse = "MOM";
strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString());
I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:
import java.util.ArrayList;
import java.util.List;
public class PalindromeRecursiveBoolean {
public static boolean isPalindrome(String str) {
str = str.toUpperCase();
char[] strChars = str.toCharArray();
List<Character> word = new ArrayList<>();
for (char c : strChars) {
word.add(c);
}
while (true) {
if ((word.size() == 1) || (word.size() == 0)) {
return true;
}
if (word.get(0) == word.get(word.size() - 1)) {
word.remove(0);
word.remove(word.size() - 1);
} else {
return false;
}
}
}
}
If the string is made of no letters or just one letter, it is a
palindrome.
Otherwise, compare the first and last letters of the string.
If the first and last letters differ, then the string is not a palindrome
Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.
The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'
check this condition
String string="//some string...//"
check this...
if(string.equals((string.reverse())
{
it is palindrome
}
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
import java.util.Scanner;
public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;
public void allSubstrings(String s){
for(int i=0;i<s.length();i++){
for(int j=1;j<=s.length()-i;j++){
String subString=s.substring(i, i+j);
palindrome(subString);
}
}
}
public void palindrome(String sub){
System.out.println("String to b checked is "+sub);
StringBuilder sb=new StringBuilder();
sb.append(sub); // append string to string builder
sb.reverse();
if(sub.equals(sb.toString())){ // palindrome condition
System.out.println("the given String :"+sub+" is a palindrome");
longestPalindrome(sub);
}
else{
System.out.println("the string "+sub+"iss not a palindrome");
}
}
public void longestPalindrome(String s){
if(s.length()>longest){
longest=s.length();
longestPalindrome=s;
}
else if (s.length()==longest){
oldPalindrome=longestPalindrome;
longestPalindrome=s;
}
}
public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String ::");
String s=sc.nextLine();
fp.allSubstrings(s);
sc.close();
if(fp.oldPalindrome.length()>0){
System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");
}
else{
System.out.println(longestPalindrome+":is the longest palindrome`````");
}}
}

Categories