Palindromes in a Statement: Java - java

I need some help with a palindrome detector that I am doing for homework. I need the user to enter a statement, so more then one word, and the program needs to detect which words are a palindrome and which ones are not. However, something in my loop is going wrong in that, it will only detect the first word then blend the others after together. I'm not sure what I'm doing wrong.
import javax.swing.JOptionPane;
public class Main {
static int numpali = 0;
public static void main(String[] args) {
// ask the user to enter a statement
String statement = JOptionPane.showInputDialog("Enter a Statement");
String reverse = "";
// Array to split the sentence
String[] words = statement.split(" ");
// Run a loop to seperate the words in the statement into single Strings
for (String word : words) {
// Print out original word
System.out.println(word + "\n");
int wordlength = word.length();
// send the word to lowercase so capitals are negligible
String wordlower = word.toLowerCase();
// Run a loop that reverses each individual word to see if its a
// palindrome
for (int t = wordlength; t > 0; t--) {
reverse += wordlower.substring(t - 1, wordlength);
wordlength--;
}
System.out.println(reverse);
// show a message if the word is a palindrome or not, and add 1 to the
// total number of palindromes
if (reverse.equals(wordlower)) {
JOptionPane.showMessageDialog(null, word + " is a Palindrome!");
numpali = numpali + 1;
}
word = "";
}
System.out.println("Number of Palindromes:" + "\n" + numpali);
}
}
I've tried to explain what its doing the best I can inside the program.

You never reset the "reverse" value inside your loop. So after the first word your just adding more characters to "reverse" every iteration.
Put
reverse = "";
inside your main for loop

Reset the value of reverse to reverse=""; just like what you have done word="";

Related

Trying to return a value in a method created in an object and the method contains for loops and if statements but can't do it

So I am asked to write a program that reads a sentence from the user, reports and removes wrong repetitions if any. By wrong repetitions I mean that a word (or more) is repeated (two occurrences or more) and that these repetition are consecutive.
`
public class checker {
private String sentence;
checker(String sentence){this.sentence=sentence;}
public String check(){
String[] word = sentence.split(" ");
for(int i=0; i<word.length; i++){
for(int j=i+1; j<word.length; j++){
if(word[i].equals(word[j])){
word[j]="error";}}}
for(int i=0; i<word.length; i++) {
if (!"error".equals(word[i])) {
System.out.print(word[i] + " ");}}
return "";}
}
***This is the output of my code: ***
Enter a Sentence: The operator did not not skip his meal
The operator did not skip his meal
BUILD SUCCESSFUL (total time: 12 seconds)
So my code does the job of finding the repeated words and prints the corrected version, but the problem is that I just can't find a way to make it print out like it is supposed to do in the sample run!
[Sample runs:
-Enter a sentence: The operator did not not skip his meal
-The sentence includes wrong repetitions.
-The sentence should be: The operator did not skip his meal
-Enter a sentence: Happy people live longer
-There are no wrong repetitions]
**I do know my problem, every time I try to write a piece of code containing any time type of loops and if statements together I just don't know to extract what I want from the loop and conditional statements, I was trying to
`
for(int i=0; i<word.length; i++){
for(int j=i+1; j<word.length; j++){
if(word[i].equals(word[j])){
System.out.println("The sentence includes wrong repetitions.\nThe sentence should be: ");
word[j]="error";}
else{
System.out.println("There are no wrong repetitions");
}
}
}
`
but I know it'll print it every time the loop gets executed!
I would really appreciate a helpful tip that I can carry with me going forward!
Thanks in advance guys!**
You don't have any mechanism by which to store your valid words so you can print them in the format you need to after your sentence evaluation is complete. I recommend storing the valid words in a StringBuilder or ArrayList as you go so you can print the resulting string when you are ready.
Here is a sample program to accomplish this using a StringBuilder. You could also use an ArrayList and call String.join(" ", wordList); to create the sentence when finished.
final String sentence = "This is an invalid invalid sentence that that needs corrected";
final String[] words = sentence.split(" ");
StringBuilder sentenceBuilder = new StringBuilder();
for (int i = 0; i < words.length; i++)
{
final String checkWord = words[i];
final boolean lastWord = i == words.length - 1;
final boolean duplicate = !lastWord && checkWord.equals(words[i + 1]);
if (lastWord || !duplicate)
sentenceBuilder.append(checkWord);
if (!lastWord && !duplicate)
sentenceBuilder.append(' ');
}
if (!sentence.equals(sentenceBuilder.toString()))
System.out.printf("The sentence includes wrong repetitions.%nThe sentence should be: %s%n", sentenceBuilder);
else
System.out.println("There are no wrong repetitions");
I faced the same problem in my assignment last week. I couldn't solve it but I had to submit something so I don't get a zero. The errors in my program is that there is a space left in place of the duplicated word, and it only detects two occurrences.
Here's the code i wrote:
String [] n= s.split(" ");
boolean check=false;
for (int i=1;i<n.length;i++){
String temp=n[i-1];
if (n[i].equals(temp) == true) {
check = true;
System.out.println("The sentence includes wrong repetitions.");
n[i]="";
System.out.print("The sentence should be: ");
for(int j=0;j<n.length;j++) {
System.out.print(n[j]+" ");
}
}
}
if (check == false)
System.out.println("There are no wrong repetitions");
}
}
Let me know if you found the solution or if you can improve my code
The insturctor sent us the solution, adding it here for future reference:
/*
CSCI300 - Solution of Assignment 1
Problem 2
*/
package repetitions;
import java.util.Scanner;
public class Repetitions {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean hasSuccessiveReptition = false; //Assume no repetitions
System.out.print("Enter a sentence: ");
// Read the whole sentence into one String:
String sentence = scan.nextLine();
//create an array of Strings to handle each word separately
String[] words = sentence.split(" ");
//Create a string to add non repetetive words to
String repetitionFreeSentence = words[0]; // add the fisrt word
for(int i = 1; i < words.length; i++)
if(words[i].equalsIgnoreCase(words[i-1])) // compare successive words
hasSuccessiveReptition = true;
else // add the word to the corrected setence
repetitionFreeSentence += " " + words[i];
if(hasSuccessiveReptition){
System.out.println("The sentence includes wrong repetitions.");
System.out.println("The sentence should be: " + repetitionFreeSentence);
}
else
System.out.println("There are no wrong repetitions");
}
}

Java Scanner Class ( System.in)

I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.

charAt(0) Not returning first number but second

Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Assignment_4_Piglatin {
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
String vowels = "aeiou";
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
if (vowels.contains(String.valueOf(word.charAt(index)))) {
System.out.print(index);
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
}
}
}
System.out.println(firstVowel);
The example seems to have some redundant code in if..else condition. If you want to print the first vowels then you can do it with a simple for loop, e.g.:
String word = userWord.next().toLowerCase();
String vowels = "aeiou";
for(int i=0 ; i<word.length() ; i++){
if(vowels.contains(String.valueOf(word.charAt(i)))){
System.out.println(word.charAt(i));
break;
}
}
Please note that you need to do toLowerCase on the actual word in order for contains to work.
There are a few problems I can see off the bat, but the one that is likely causing this error is in these lines:
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
Think about what this is doing. First, you are making a String out of the index value, then you are saying that the first vowel is at the 0th index of that string.
Think of this example: hello
The program will run and assign "4" to firstNumber and firstVowel which isn't what you want.
However, if you only have one vowel, your program will "work".
What happens if you have over ten vowels? I know this isn't a realistic example, but say it happens. Your program will assign the index of the last vowel to firstNumber (say it's 15), then it will assign the first character of that to firstVowel (1). This doesn't make much sense at all, does it, especially if you don't have a vowel in index 1.
The main problem you are encountering for words less than 10 letters in length is that you are not just outputting the second number, you are outputting the last one. One way I like to deal with this is to go through the code and put in print statements where I'm not sure what a certain value is. For example, I'd put another print statement in your loop which tells you what letter you're looking at, like so:
System.out.println("LETTER: "+ String.valueOf(word.charAt(index)));
This will help you avoid confusion. The proper way to do this problem would be to use a break statement, such as in Darshan's answer. Alternatively, you could use the properties of the for loop:
firstVowel = "";
for (int index = 0; index < word.length() && firstVowel == ""; index++) {
CODE
}
Note that the second part of the for loop is a conditional statement. You already know that this can be used to cycle through the word's characters, but you can insert any logical statement there that you want. For this example, I set the default value of firstVowel to "" (setting it to null is a faux-pas, but that's another story). Then, each time the loop runs, it checks to see if the value of firstVowel has been changed, which will of course happen on the first time a vowel is run through the loop.
So in short, you need to modify the two lines at the beginning of my post and you need to find a way to break your loop when you find the first vowel. One solution has been given here, and another in Darshan Mehta's post.
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
ArrayList<Character> vowels = new ArrayList<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
char indchar = word.charAt(index);
if (vowels.contains(word.charAt(index))) {
System.out.println(index);
firstVowel = Character.toString(word.charAt(index));
System.out.println(firstVowel);
index = word.length();
}
}
}
}
}
This is how I would do it. I changed the vowels String to an ArrayList so you can easily check if the char in the String word with the index is a vowel and the code works absolutely fine. It returns you the index where the first vowel is and what vowel it is.

For loop iterating through string and adding/replacing characters

I need to write for loop to iterate through a String object (nested within a String[] array) to operate on each character within this string with the following criteria.
first, add a hyphen to the string
if the character is not a vowel, add this character to the end of the string, and then remove it from the beginning of the string.
if the character is a vowel, then add "v" to the end of the string.
Every time I have attempted this with various loops and various strategies/implementations, I have somehow ended up with the StringIndexOutOfBoundsException error.
Any ideas?
Update: Here is all of the code. I did not need help with the rest of the program, simply this part. However, I understand that you have to see the system at work.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class plT
{
public static void main(String[] args) throws IOException
{
String file = "";
String line = "";
String[] tempString;
String transWord = ""; // final String for output
int wordTranslatedCount = 0;
int sentenceTranslatedCount = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Welcome to the Pig-Latin translator!");
System.out.println("Please enter the file name with the sentences you wish to translate");
file = stdin.nextLine();
Scanner fileScanner = new Scanner(new File(file));
fileScanner.nextLine();
while (fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
tempString = line.split(" ");
for (String words : tempString)
{
if(isVowel(words.charAt(0)) || Character.isDigit(words.charAt(0)))
{
transWord += words + "-way ";
transWord.trim();
wordTranslatedCount++;
}
else
{
transWord += "-";
// for(int i = 0; i < words.length(); i++)
transWord += words.substring(1, words.length()) + "-" + words.charAt(0) + "ay ";
transWord.trim();
wordTranslatedCount++;
}
}
System.out.println("\'" + line + "\' in Pig-Latin is");
System.out.println("\t" + transWord);
transWord = "";
System.out.println();
sentenceTranslatedCount++;
}
System.out.println("Total number of sentences translated: " + sentenceTranslatedCount);
System.out.println("Total number of words translated: " + wordTranslatedCount);
fileScanner.close();
stdin.close();
}
public static boolean isVowel (char c)
{
return "AEIOUYaeiouy".indexOf(c) != -1;
}
}
Also, here is the example file from which text is being pulled (we are skipping the first line):
2
How are you today
This example has numbers 1234
Assuming that the issue is StringIndexOutOfBoundsException, then the only way this is going to occur, is when one of the words is an empty String. Knowing this also provides the solution: do something different (if \ else) when words is of length zero to handle the special case differently. This is one way to do this:
if (!"".equals(words)) {
// your logic goes here
}
another way, is to simply do this inside the loop (when you have a loop):
if ("".equals(words)) continue;
// Then rest of your logic goes here
If that is not the case or the issue, then the clue is in the parts of the code you are not showing us (you didn't give us the relevant code after all in that case). Better provide a complete subset of the code that can be used to replicate the problem (testcase), and the complete exception (so we don't even have to try it out ourselves.

Writing a program to count spaces in a phrase

I'm trying to write a program where a user would enter a phrase, and the program would count the blank spaces and tell the user how many are there. Using a for loop but i'm stuck, could someone help me out?
import java.util.Scanner;
public class Count
{
public static void main (String[] args)
{
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
for(ch=phrase.charAt()
// and count the blank spaces
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}
The for loop for counting spaces would be written as follows:
for(int i=0; i<phrase.length(); i++) {
if(Character.isWhitespace(phrase.charAt(i))) {
countBlank++;
}
}
It reads as follows: “i is an index, ranging from the index of the first character to the index of the last one. For each character (gotten with phrase.charAt(i)), if it is whitespace (we use the Character.isWhitespace utility function here), then increment the countBlank variable.”
Just wondering, couldn't you just split the string entered by blank spaces and take the length of the array subtracted by 1?
In C# it would be as trivial as
string x = "Hello Bob Man";
int spaces = x.Split(' ').Length - 1;
Pretty sure java has a split? Works even if you have two contiguous spaces.
You have probably problem with that for each loop
char[] chars = phrase.toCharArray(); Change string into array of chars.
for(char c : phrase.toCharArray()) { //For each char in array
if(Character.isWhitespace(c) { //Check is white space.
countBlank++; //Increment counter by one.
}
}
or
for(int i =0; i <phrase.lenght(); i++) {
if(Character.isWhitespace(phrase.charAt(i)) { //Check is the character on position i in phrase is a white space.
countBlank++; //Increment counter by one.
}
}
You have to complete for cycle and count spaces
//replace this lines
for(ch=phrase.charAt()
// and count the blank spaces
//to this lines
for (int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == ' ') countBlank++;
}
Loop through the characters in the string.
Check if the character is a space (char value = 32 or ch == ' ')
If space, add to countBlank, otherwise continue
Display the results.
You might look at the String and Character classes in the Java documentation for assistance.
I'm not very familiar with java, but if you can access each character in the string.
You could write something like this.
int nChars = phrase.length();
for (int i = 0; i < nChars; i++) {
if (phrase.charAt(i) == ' ') {
countBlank++;
}
}
This is at the following Java Tutorials
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class SplitDemo2 {
private static final String REGEX = "\\d";
private static final String INPUT = "one9two4three7four1five";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
String[] items = p.split(INPUT);
for(String s : items) {
System.out.println(s);
}
}
}
OUTPUT:
one
two
three
four
five
The regex for whitespace is \s
Hope that helps.

Categories

Resources