Palindrome checker - spacing - java

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.

Related

How do you, using a set of random given letters, check if a word is created with only those given letters

In Java, I am supposed to make a word game where one is supposed to make letters with a given set of random letters. I have already wrote the code to find the letters (Variable is String Letters ), but I am having trouble checking if the word chosen by the player (String word), is actually created using the given letters? I have a txt file of all the English words in the English language, and this is what I am basing it off if it is a word. How do I do this? I am pretty sure it has something to do with checking the index, or using the built in command contains at.
I have already tried to search for this. However other questions used C-Language or Python. I have found 1 Java explanation, however I am new to coding and do not understand the code and variables they used.
This is an example of where I need help
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
Full method.
public static void getWord(String letters) {
int trys = 0;
int trysLeft = 5;
System.out.println("Input a word that you can make with those letters");
while (trys < 5) {
String word = getString(); //getString is a method where user can input a desired string
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
}
else if (Words.contains(word) == false) {
System.out.println("That is not a real word! Please enter a word that you can make with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
else if (Words.contains(letters) == false) {
System.out.println("You can not make a word with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
}
}
You need to check the cointains for each letter. If you send a charSeq, example { 'a' , 'b', 'd' }, java will try to find if your string contains completely "abd"
One way to do it is to sort the letters in your letter list and your word and see if your word is contains in the available letters, like this:
public static void main(String args[]) {
String letters = sort("haat");
System.out.println("Is a word: " + letters.contains(sort("hat")));
}
public static String sort(String s)
{
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
There are many techniques that you could use to implement this class project.
Here is one:
Build a Map from the input letters. The key of the map should be a Character and the Value of the map should be the count of letters.
Build a Map from the word guess. Again, the key of the map should be a Character and the Value of the map should be the count of letters.
Compare the maps. If they are equal, then the word is constructed from exactly the letters in the input letters string.

How to reverse a string that has already been reversed?

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:

Prevent the user entering numbers in java Scanner?

I am having some trouble preventing the user from entering numbers with the scanner class. This is what I have:
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word;
String inverse = "";
System.out.println("Write a sentence or word: ");
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Not valid! Try again: ");
input.nextLine();
}
word = input.nextLine();
word = word.replaceAll("\\s+","");
word = word.toLowerCase();
int length = word.length();
length = length - 1;
for (int i = length; i >= 0; i--) {
inverse = inverse + word.charAt(i);
}
if (word.equals(inverse)) {
System.out.println("Is a palindrome.");
} else {
System.out.println("Is not a palindrome.");
}
}
}
Basically when I enter a word or sentence I want it to check if it has any numbers anywhere in the input, if it has then you need to enter another one until it doesn't. Here is an example of output:
Write a sentence or word:
--> 11
Not valid! Try again:
--> 1 test
Not valid! Try again:
--> test 1
Is not a palindrome.
As you can see it works for most cases, but when I enter a word FIRST and then a space followed by a number it evaluates it without the number. I am assuming this is happening because in the while loop is checking for only input.hasNext but it should be input.hasNextLine I believe to check the entire string. However I cannot have any arguments if I do that. Help much appreciated!
Change your regex from: [A-Za-z]+ to ^[A-Za-z]+$ in order to prevent numbers anywhere in the input-string

How to print out the number of capital letters in a string - java

So I have this program I need to write. I'm, supposed to get an input string from a user and then print out how many capital letters and how many lowercased letters are in the string. I've looked everywhere in the book that I have and I just can't seem to find anything about how to print out the uppercase and lowercase letters. I've been doing a lot of googling as well and I couldn't find anything useful.
Anyway here's my code:
import java.util.Scanner; //calls out the method to get input from user
public class Verk1 {
public static void main(String args[])
{
Scanner innslattur = new Scanner(System.in); //input gotten from user
System.out.println("Sláðu inn textabrot í há- og lágstöfum.");
System.out.println("Forritið mun þá segja þér hve margir stafir eru af hverri gerð.");
System.out.println("Textabrot: ");
//The printouts before tell the user to enter in a string, the program will then print out //how many upper- and lowercase letters there are.
String strengur = innslattur.nextLine();
String hastafir = "";
for (int i=0; i<hastafir.length();i++);
{
System.out.println("Í textabrotinu eru " + hastafir + " hástafir");
}
}
}
I know the code is faulty/doesn't work, but do any of you know how I get the number of uppercase- lowercase letters to print them out?
Thanks in advance!
Cheers
I haven't tested it but I would look to do something like this.
String text = "This IS My TEXT StrinG";
int upperCaseCounter = 0;
int lowerCaseCounter = 0;
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
upperCaseCounter++;
}
else if(Character.isLowerCase(text.charAt(i)))
{
lowerCaseCounter++;
}
}
System.out.println("Total Uppercase Characters: " + upperCaseCounter);
System.out.println("Total Lowercase Characters: " + lowerCaseCounter);
You can do their fairly easily if you convert the string to a char[] first. You can then use the isUpperCase(char c) for each character in the string. http://www.tutorialspoint.com/java/character_isuppercase.htm
For some strange reason your for loop is referring to an empty string you've just declared, rather than the string you just read in from the user. However, if you change that, inside your loop you can get at the individual characters in the string with strengur.charAt(i) and you can test whether a letter is capital with Character.isUpperCase(ch) and you can check for a lower case letter with Character.isLowerCase(ch).
public void printCapsAndLowercaseCounts(String s) {
int uppercase = 0;
int lowercase = 0;
if (s != null) {
String s1 = s.toUpperCase();
String s2 = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s1.charAt(i) ^ s.charAt(i) == s2.charAt(i)) {
if (s.charAt(i) == s1.charAt(i)) uppercase++;
else lowercase++;
}
}
}
System.out.println(uppercase + " " + lowercase);
}
Seems like this would do the trick, assuming you're not doing it an excessive amount. Just use a temporary string, and get the difference between the two:
int capLetterCount = originalString.length() - originalString.replaceAll("[A-Z]", "").length();

Using methods to check for palindromes

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()));
}
}

Categories