I have to use methods to test a sentence for palindromes and I have got most of it done but it will only do the first word in the string and won't move on to the next one. I believe its something got to do with the spaces, if anyone could help that'd be great. Also I haven't studied arrays so I'd appreciate if arrays were not used.
class palindromeTesting
{
public static void main(String[] args)
{
String userInput;
String goodWords;
String palindromes;
System.out.println("Please enter a sentance to be tested for palindrome: ");
userInput = EasyIn.getString();
userInput += " " ;
goodWords = charsCheck(userInput); //Calling a method to check if any word contains more than letters.
palindromes = palinCheck(goodWords); //Checking the good words to see if they're palindromes.
System.out.println("The valid palindromes are " + palindromes);
} //Main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
public static String charsCheck(String userInput)
{
String validWords;
String firstWord;
Boolean goodWord;
int spacePos;
char letter;
spacePos = userInput.indexOf(" ");
validWords = "";
while(spacePos > 0)
{
firstWord = userInput.substring(0 , spacePos);
goodWord = true;
for(int index = 0 ; index < firstWord.length() && goodWord == true ; index++)
{
spacePos = userInput.indexOf(" ");
letter = Character.toUpperCase(firstWord.charAt(index));
if(letter < 'A' || letter > 'Z' )
{
goodWord = false;
}
} //for
if(goodWord == true)
{
firstWord = firstWord + " ";
validWords = validWords + firstWord;
}
userInput = userInput.substring(spacePos + 1);
spacePos = userInput.indexOf(" ");
} //While
return validWords;
} //charsCheck main
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
public static String palinCheck(String goodWords)
{
String firstWord;
String validPalins = "";
String backward = "";
int spacePos;
spacePos = goodWords.indexOf(" ");
while(spacePos > 0)
{
firstWord = goodWords.substring(0 , spacePos);
for(int i = firstWord.length()-1; i >= 0; i--)
{
backward = backward + firstWord.charAt(i);
}
if(firstWord.equals(backward))
{
validPalins = validPalins + firstWord;
}
goodWords = goodWords.substring(spacePos + 1) ;
spacePos = goodWords.indexOf(" ") ;
}//While
return validPalins;
} //palinCheck main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
} //Class
If you believe the issue are spaces, you could always remove all spaces (and any other unwanted characters) with the replaceAll() method (check out the API). Say you have word1 and word2 you'd like to compare to see if they are palindromes, then do the following:
String word1 = "du mb";
String word2 = "b,mu d";
word1 = word1.replaceAll(" ", "");//replace it with empty string
word1 = word1.replaceAll(",", "");//even if the comma doesn't exist, this method will be fine.
word2 = word2.replaceAll(" ", "");
word2 = word2.replaceAll(",", "");
Once you've gotten ridden of unnecessary characters or spaces, then you should do the check. Also, you could always use Regex expressions for this kind of task, but that may be a bit difficult to learn for a beginner.
Also, I recommend using for loops (can probably be done in one for loop, but nested loops will do) instead of while loop for this task. Check out this example.
Sidenote:
Also I haven't studied arrays so I'd appreciate if arrays were not
used.
Strings are essentially char arrays.
The problem you described is actually not what is happening; your code does indeed move on to the next word. For my test, I used the test input Hi my name is blolb.
The problem is in your palinCheck method. You are using the backward variable to reverse the word and check whether it and firstWord, are equal. However, you aren't resetting the backward variable back to a blank string in the loop. As a result, you're constantly adding to whatever was in there before from the previous loop. At the end of the method, if I examine the content of backward using my test string above, it actually looks like iHymemansiblolb.
To solve this, simply declare String backward inside the while loop, like so:
while(spacePos > 0) {
String backward = "";
// rest of loop
Quick side note:
During the run of the palinCheck method, you're changing the goodWords parameter each iteration when you do this:
goodWords = goodWords.substring(spacePos + 1) ;
While this is technically acceptable (it has no effect outside of the method), I wouldn't consider it good practice to modify the method parameter like this. I would make a new String variable at the top of the method, perhaps call it something like currentGoodWords or something like that, and then change your line to:
currentGoodWords = goodWords.substring(spacePos + 1) ;
Also, I assume this is homework, so if you are allowed to use it, I would definitely take a look at the StringBuilder#reverse() method that Elliot Frisch mentioned (I admit, I never knew about this method before now, so major +1s to Elliot).
I had this code written as a personal project quite a while ago on palindrome using the shortest amount of code. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}
Related
I have the following code that takes 2 strings as inputs and returns Boolean on whether they're anagrams:
import java.util.ArrayList;
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print ("Enter string 1: ");
String str1 = sc.nextLine();
System.out.print ("Enter string 2: ");
String str2 = sc.nextLine();
boolean check = isAnagram (str1, str2);
System.out.println ("Anagram check for '" + str1 + "' and '" + str2 + "': " + check);
sc.close();
}
public static boolean isAnagram (String s1, String s2) {
if(s1.length() != s2.length())
return false;
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
ArrayList<String> myList = new ArrayList<String>();
for(int i = 0; i < s2.length() ; i++ ){
myList.add(String.valueOf(s2.charAt(i)));
}
for(int i = 0; i < s1.length();i++){
for(int j = 0; j < myList.size(); j++){
if(myList.get(j).equals(String.valueOf(s1.charAt(i)))){
myList.remove(j);
j = 0;
break;
}
}
}
return myList.isEmpty();
}
}
It is somewhat limited though, I'm trying to expand it to work for the following cases:
- different cases i.e. eager == AGREE
- single word with whitespaces i.e. eager == a g ree
- different amounts of whitespace i.e. " eager" == agree
Is there a nice and clean way to integrate this into already written code above without much pain and re-writing. Any help much appreciated. Thanks.
Yes there is. Regex to the rescue! You can use the String built in .replaceAll(). Passing it the \s value will remove all spaces and characters not printed such as \n. I would suggest that during comparison you use something like the following:
string1.replaceAll("\\s","").equals(string2.replaceAll("\\s",""));
personally I would do the following
use trim() to remove leading and traiing whitespace
use replace to remove whitespaces
use toLowerCase() to make the text lower case
convert the Strings into an array list of characters
sort the arrays
compare the arrays - if they are the same then you have an anagram
I made a program that lets a user enter in a word or a phrase or a sentence and reverse it and display the result.
My issue is that when I run it it does reverse it but it reverses the words when all I want to do is keep the words as they were inputted and just reverse them.
Here is what I have currently
//import statements
import java.util.*; //for scanner class
// class beginning
class WordReverser {
public static void main(String[] args ) {
//Declare variables area
String original, reverse = "";
Scanner in = new Scanner(System.in);
boolean blankString = false;
public StringBuilder reverse();
// beginning message to user to explain the program
System.out.println("Welcome to my reverse word program!");
System.out.println("Please enter in a word or a phrase and see it reversed: ");
//main code and calculations to do
while (!blankString){
System.out.println("Enter a string to reverse");//Collect inputs from user.
original = in.nextLine();
if (original.equals(""))
{
blankString = true ;
}
else {
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);//Output results here
}
}
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
Clearly a homework question, so I'll give you a shove in the right direction, but I won't give the full answer. You need to reverse one word at a time and not the whole string.
You need something that implements this pseudo code:
original = getStringFromUser();
words[] = breakIntoWords(original);
foreach word in words {
reversed = reverse(word);
print reversed;
}
reverse(string word)
{
return reversed version of the input
}
breakIntoWords(sting sentence)
{
return array with each word as a sep.element
}
If you read the docs, you may find reverse and breakIntoWords are already there for you, so you just need to call the right methods.
The key to solving problems is learning how to break them down into smaller pieces that are easier to solve. This is a good problem solving technique and is at the heart of programming.
You know how to reverse the letters in a sentence. You want to reverse the letters in each word, but leave the words in their original order. Or, to say it another way, you want to:
Split the sentence into separate words.
Reverse each word one by one.
Combine the words back together into a sentence.
Hopefully each of these steps is more manageable. If not, think about how you can break them into even smaller steps. For instance, for #2 maybe you need a loop and then something inside that loop.
Do you want to reverse the word order? In this case you'll have to split the input string at " ".
To do this, your else-block should be
String[] words = original.split(" ");
for(int i = words.length-1; i>=0; i--)
reverse += words[i] + " ";
System.out.println("Reverse of entered string is: "+reverse);
I see 2 ways of dealing with this quickly if not too elegantly
easiest thing to do would be to create a 3rd variable called something like String originalWords that gets appended to from stdin in the loop.
Reuse the existing 'original' String to do the same as above and then loop it in reverse in a second loop.
You can split the input string into separate array of words and then reverse each word in the array separately.
Refer this for code.
I have refactored your code a little bit to solve your issue. First I put your reverse logic in a separate method
public static String reverse(String strToReverse) {
String original = strToReverse, reverse = "";
boolean blankString = false;
if (original.equals(""))
{
blankString = true ;
}
else {
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
}
return reverse;
}
Second I splitted your string into words (assuming the words are separated by simple spaces)
public static void main(String[] args ) {
//Declare variables area
String original, reverse = "";
Scanner in = new Scanner(System.in);
boolean blankString = false;
//public StringBuilder reverse();
// beginning message to user to explain the program
System.out.println("Welcome to my reverse word program!");
System.out.println("Please enter in a word or a phrase and see it reversed: ");
//main code and calculations to do
while (!blankString){
System.out.println("Enter a string to reverse");//Collect inputs from user.
original = in.nextLine();
if (original.equals(""))
{
blankString = true ;
}
else {
String[] words = original.split(" ");
String[] reversedWords = new String[words.length];
StringBuilder reverseBuilder = new StringBuilder();
for (int index = 0; index < words.length; index++) {
reversedWords[index] = reverse(words[index]);
reverseBuilder.append(reversedWords[index] + " ");
}
System.out.println("Reverse of entered string is: "+reverseBuilder.toString());//Output results here
}
}
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
Here is an execution example:
I have a program where I am typing a Java program to check if the String entered is a palindrome. I have 2 problems going on that I can not for the life of me seem to figure out.
I have typed out the code so that it will tell me if it is a palindrome when all lowercase letters and no spaces involved. Any time I enter a palindrome with a space anywhere in it, it will tell me it is not a palindrome. Think I am just missing one little piece of code to make it work.
import java.util.Scanner;
public class HW3 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String word;
String backwards = "";
System.out.println("Enter a word or phrase and I'll tell you if it's a palindrome");
word = keyboard.nextLine();
int length = word.length();
for (int i = length - 1; i >= 0; i--) {
backwards = backwards + word.charAt(i);
}
if (word.equalsIgnoreCase(backwards)) {
System.out.println(word + " is a palindrome!");
}
else {
System.out.println("That is not a palindrome!");
System.exit(0);
}
System.out.println("Done!");
}
}
You seem to want to remove spaces from your strong. To do so, use the replace() method:
word.replace(" ", "");
Try removing all spaces before performing the palindrome check.
word = word.replaceAll("\\s","");
Your program works as expected. (At least how I expect it to work; "taco cat" does not equal "tac ocat" so it should not be regarded as a palintrome.)
If you want to disregard from spaces, you could do
word = word.replaceAll("\\s", "");
right after reading the input string.
I am currently in a computer programming class and at a dead end for "creating a template" for this 2-person hang man game.
First, person#1 is prompted for a phrase (contains all lowercase)
Then, I must take whatever phrase they choose and turn it into a template with all ?'s.
Then, as person#2 guesses letters, I must "reveal" the phrase and have the ?'s turn into the phrase letters.
I can't get past turning it into the template though. An example is:
person#1's phrase: "hello world"
desired template outcome: "????? ?????"
This is what I have so far... I'm having trouble at public static String createTemplate(String sPhrase)
import java.util.Scanner;
public class Program9
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
Scanner stdIn = new Scanner (System.in);
int cnt = 0; //counter is set to zero
String sPhrase;
boolean def;
System.out.print("Enter a phrase consisting of only lowercase letters and spaces: ");
sPhrase = scanner.nextLine(); //reads into variable set to Scanner.nextLine()
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String template = createTemplate(sPhrase); //will run through "createTemplate" and show whatever on there.
do
{
char guess = getGuess(stdIn); //will run through "getGuess" and show whatever SOP and return from that. WORKS.
cnt = cnt + 1; //counts the guess
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String updated = updateTemplate(template, sPhrase, guess); //runs throuhgh and prints updated template
} while (!exposedTemplate(sPhrase)); //will loop back if updated template still has ?'s
System.out.println("Good job! It took you " + cnt + " guesses!");
}
public static String createTemplate(String sPhrase)
{
String template = null;
String str;
sPhrase.substring(0, sPhrase.length()+1); //not sure if +1 needed.
sPhrase.equals(template);
//THIS IS WHERE IM HAVING PROBLEMS
}
public static char getGuess(Scanner stdIn)
{
//repeatedly prompts user for char response in range of 'a' to 'z'
String guess;
do
{
System.out.print("Enter a lowercase letter guess : ");
guess = stdIn.next();
} while (Character.isDigit(guess.charAt(0)));
char firstLetter = guess.charAt(0);
return firstLetter;
}
public static String changeCharAt(String str, int ind, char newChar)
{
return str.substring(0, ind) + newChar + str.substring(ind+1);
//freebie: returns copy of str with chars replaced
}
public static String updateTemplate(String template, String sPhrase, char guess)
{
//will have to include changeCharAt
}
public static boolean exposedTemplate(String template)
{
// returns true exactly when there are no more ?'s
}
}
A simple solution would be:
public static String createTemplate(String sPhrase)
{
return sPhrase.replaceAll("[a-zA-Z]", "?");
}
the replaceAll method of the String class in Java replaces all parts of the string that match the supplied regular expression with a string (in this case ?)
Learning regular expressions (known as regexes) may not be in the scope of this assignment, but is a very useful skill for all computer programmers. In this example I've used the regular expression [a-zA-Z] which means replace any upper or lower case character, however you could also use a character class like \\w.
There is an excellent tutorial on Java regexes here: https://docs.oracle.com/javase/tutorial/essential/regex/
You'll need a for-loop, you'll need to check each character of the phrase, String#charAt should help. If the character is not a space, you would append an ? to the template, otherwise you'll need to append a space...
See The for Statement for more details...
StringBuilder sb = new StringBuilder(sPhrase.length());
for (int index = 0; index < sPhrase.length(); index++) {
if (sPhrase.charAt(index) != ' ') {
sb.append("?");
} else {
sb.append(" ");
}
}
sTemplate = sb.toString();
Equally you could use...
StringBuilder sb = new StringBuilder(sPhrase.length());
for (char c : sPhrase.toCharArray()) {
if (c != ' ')) {
sb.append("?");
} else {
sb.append(" ");
}
}
sTemplate = sb.toString();
But I thought the first one would be easier to understand...
Just use a regex and String.replaceAll() method:
public static String createTemplate(String sPhrase)
{
return sPhrase.replaceAll(".", "?");
}
In this example, the first parameter is a regex, so "." matches all characters. The second parameter is the string to replace all regex matches with, a "?".
I'm trying to use utilize a space " " to separate words within a String that a user inputs. For this example, the user input String might be "Random Access Memory" or "Java Development Kit." Regardless of the entered string, the space will separate each word. In addition to this, I cannot use .split or an array, since those are the most common solutions I have found thus far. Only utilizing .substring is allowed. In my failed attempts, I have only been capable of obtaining the first inputted word (ex. "Random"), but cannot separate the second and third words (ex. "Access Memory"). I'm not going to publish my failed attempts, but am asking if you could please provide the code for separating both the second and third words entered? Thanks.
P.S. I know this is used to create acronyms, I can do that part, just need to identify each substring.
import javax.swing.*;
public class ThreeLetterAcronym
{
public static void main(String[] args)
{
String wordsInput, initialInput;
String first = "";
String second = "";
String third = "";
int firstWord;
int secondWord;
int wordLength;
int secondWordLength;
char c;
wordsInput = JOptionPane.showInputDialog(null, "Please enter three words");
initialInput = wordsInput;
wordLength = wordsInput.length();
firstWord = 0;
secondWord = 0;
while(firstWord < wordsInput.length())
{
if(wordsInput.charAt(firstWord) == ' ')
{
first = wordsInput.substring(0,firstWord);
second = wordsInput.substring(firstWord + 1, wordsInput.length());
//I know that this is the spot where the last two words are displayed in the output, this is
//the closest I have been to displaying anything relevant.
firstWord = wordsInput.length();
}
++firstWord;
}
JOptionPane.showMessageDialog(null, "Original phrase was: "
+ initialInput + "\nThree letter acronym is: " + first + second);
}
}
Just to separate in words without (strangely) using Spring.split:
String myString = "Random Access Memory";
int begin = 0;
int end;
while((end = myString.indexOf(" ", begin)) != -1) {
System.out.println(myString.substring(begin, end));
begin = end + 1;
}
System.out.println(myString.substring(begin));
String tmp = wordsInput.trim();
int spaceIndex = tmp.indexOf(" ");
first = tmp.substring(0,spaceIndex);
tmp = tmp.substring(spaceIndex+1);
tmp = tmp.trim();
spaceIndex = tmp.indexOf(" ");
second = tmp.substring(0, spaceIndex);
tmp = tmp.trim();
third = tmp.substring(spaceIndex+1);
You can use a loop to improve the code. I hope that will be helpful.