I have the program made up until the point where it has to ignore and punctuations and spaces in the thread and I was wondering if anyone could help me with the coding for that? What I've been trying out doesn't seem to be working. Here is what I have so far:
import java.util.Scanner;
public class PalindromeTester
{
public static void main (String[] args)
{
String str, another = "y";
int left, right;
char charLeft, charRight;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome: ");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while (left < right)
{
charLeft = str.charAt(left);
charRight = str.charAt(right);
if (charLeft == charRight)
{
left++;
right--;
}
else if (charLeft == ',' || charLeft == '.' ||
charLeft == '-' || charLeft == ':' ||
charLeft == ';' || charLeft == ' ')
left++;
else if (charRight == ',' || charRight == '.' ||
charRight == '-' || charRight == ':' ||
charRight == ';' || charRight == ' ')
right--;
else
break;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
Just to clarify what Jim Garrison said, the regex you need is the following
String m = "Madam, I'm'',.,.'' Adam";
m = m.toLowerCase().replaceAll("\\W", "");
This will leave only letters and digits and remove whitespace and punctuation, i.e. m will become "madamimadam" and you can run you regular palindrome test on that string.
You can learn more about regular expressions here
This looks like a really old post but I think I stumbled upon a simpler solution for a palindrome test. This checks the first and last characters and moves inwards and exits the program as soon as the characters do not match.
public class CharTest {
public static void main(String[] args) {
//converts string to lowercase and replaces everything except numbers
// and alphabets
String s = "Niagara. O roar again!".toLowerCase().replaceAll("\\W", "");
int j=0;
int k = s.length() - 1;
while(j < s.length() / 2) { //loops until half the length of the string if
//even and floor value if odd.
if (s.charAt(j++) != s.charAt(k--)){//check for first and last chars
//and go inwards. if char do not match print 'Not a Palindrome' and exit
System.out.println("Not a Palindrome");
System.exit(0);}
}
System.out.println("Palindrome"); //if every chars match print "Palindrome"
}
}
This code for determine if a word is a palindrome can be much more simplified. Find updated Code
String word;
int z;
int y = 0;
int i = 0;
char letter;
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
word = input.nextLine();
word = word.replaceAll("\\s+", "");
word = word.toLowerCase();
z = word.length()-1;
while (i <= z){
if ((letter = word.charAt(i)) == (letter = word.charAt(z-i))){
y += 1;
}
i += 1;
}
if (y == (z+1)){
System.out.println("The word IS a palindrome");
}
else{
System.out.println("The word is NOT a palindrome");
}
}
}
You could simplify the code significantly by removing all the spaces and punctuation before you start. Look at String.replaceAll(regex,replacement). You would write a regular expression to match blanks and punctuation, and provide an empty string ("") as the replacement. This will return a new string containing the original minus the characters you want to ignore.
This is the programming assignment from the Java Software Solutions (PP3.11) that I assign my students. Ironically the teacher solution uses Character.isLetterOrDigit(___) (which is never mentioned in the book) and uses methods to get rid of spaces and punctuation (having not even taught methods at that point in the book), and char is not an official part of the AP CS subset. Silly publishers.
Look at char's documentation entry. Specifically the isLetterOrDigit method. If that method returns false, then it's punctuation or a space. There are other methods in there as well that can help with that.
Your Problem: You are not ignoring the case of the letters. So if you try Able was I, ere I saw Elba, it will not come back correctly, although it is a true palindrome.
Related
I'm doing an assignment that converts a string sentence into pig latin.
I've planned and written all the code but I get this error:
String index is out of range
Below is my code:
import java.util.*;
public class project1d {
public static void main(String[] args){
System.out.println("This is a pig latin translator. Enter a sentence to convert.");
Scanner console = new Scanner(System.in);
pigLat(console);
}
public static void pigLat(Scanner console){
String sentence = console.next();
int start = 0;
int end = 0;
int counter =0;
while(sentence.length()>0){
while(end<sentence.length()-1){
while(sentence.charAt(counter+1)!=' '){
counter++;
end = counter;
}
String word = sentence.substring(start,end);
int index= 0;
char letter= word.charAt(index);
while (letter != 'a' || letter != 'e' || letter != 'i' ||
letter != 'o' || letter != 'u'){
index++;
}
System.out.print(word.substring(index,word.length()-1)+"-");
System.out.print(word.substring(0,index-1)+"ay");
counter++;
start=end+1;
}
System.out.println("Do you wanna put in another? Press ENTER to quit");
sentence = console.next();
}
}
}
I think the third while loop is increasing one too many times, but I can't figure out how to fix this or if that's even the problem.
The actual java errors are listed below:
- java.lang.StringIndexOutOfBoundsException: String index out of range: 4
- at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
- at java.base/java.lang.String.charAt(String.java:693)
- at project1d.pigLat(project1d.java:15)
- at project1d.main(project1d.java:6)
Any help is appreciated.
Unfortunately, there are many things wrong with the code, aside of whether it does what it's intended to do or not.
You're increasing the indexes and checking the value without confirming whether those indexes are valid.
You are not clearing the variables before using them again after the first iteration of the whole thing.
You're increasing the index but you got an infinite loop at the letter check because you're not changing the letter when you increase the index.
The letter check is checking conditions that overlap - letter!= a || letter!=e will always be true, thus this makes it an infinite loop too.
As Andy pointed out: String sentence = console.next(); will only read a single word. Use nextLine instead.
Please try:
public static void pigLat(Scanner console){
String sentence = console.next();
int start = 0;
int end = 0;
int counter =0;
while(sentence.length()>0){
start = 0; end = 0; counter = 0;
while(end<sentence.length()-1){
while(sentence.length()>counter+1 && sentence.charAt(counter+1)!=' '){
counter++;
end = counter;
}
String word = sentence.substring(start,end);
if(word.length()>0){
int index = 0;
char letter = word.charAt(index);
while(index+1<word.lenght() && letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o' && letter != 'u'){
index++;
letter = word.charAt(index);
}
System.out.print(word.substring(index,word.length()-1)+"-");
System.out.print(word.substring(0,index-1)+"ay");
}
counter++;
start=end+1;
}
System.out.println("Do you wanna put in another? Press ENTER to quit");
sentence = console.nextLine();
}
It's just natural that your code has some mistakes, as you're still learning how to do that properly. Keep it up ;)
While creating a word counter in java through collecting user input from a scanner I've been running into the error of having my program display that there was one extra word entered when there is a space entered in after the final word in the char. Is there a way to check the user input for a space and remove it before entering my word count loop?
Right after...
String userinput = wordcounter.nextLine();
... add this line:
userinput = userinput.trim();
It should fix the problem, since the function trim() gets rid of any blank spaces at the beginning or ending of the string.
Try something like this:
public static void main(String[] args) {
int word = 0;
System.out.println("Enter a string: ");
Scanner wordcounter = new Scanner(System.in);
while (wordcounter.hasNext()) {
wordcounter.next();
word++;
}
System.out.println("You hav entered " + word + " words.");
}
Moreover there are many functions in Java that you can use here to do this very easily like using string tokenizer, etc. But if you want to make changes in the above program, you could simply do a simple check statement before the main if condition that if the I == length-1, because this means that you are at the last character and there is nothing after this, for this case you could just continue or break. Hopefully I solved your query, do tell in case you need more clarification...
One possible way: use regex after you trim your input.
String text = "I turned myself into a pickle Morty! :)";
String[] words = text.split("([\\W\\s]+)");
int count = 0;
for (String word: words) {
count++;
}
System.out.println("You have entered " + count + " words!");
Scanner in = new Scanner (System.in);
System.out.println("Write something");
String x = in.nextLine();
char y;
char z;
int n =1;
boolean t = true;
boolean f = false;
boolean o = false;
for (int i = 0; i<x.length();i++){
y = x.charAt(i);
if(t){
if(' ' == y){n--;}
else if(y != ' '){ t=false; f = true;}
}
if(' ' == y){n++;}
if(o){
z = x.charAt(i-1);
if(' ' == y && ' '== z){n--;}
}
if (o){
if(' ' == y && i == x.length()-1){n--;}
}
if(f){o = true;}
}
System.out.println(n);
This actually works lol
I'm a beginner at Java and I've been working on this puzzle for a while and just can't seem to get it right.
I want a user to enter a word, any word, and for a program to go through the characters in the String one by one, and if the first character is a vowel, the next 2 characters are to be erased in the String.
After the characters have been erased, the program will go to the next character and perform the same test. If a vowel, erase the next two, if not, just print the character and move on to the next one.
For example, a random word like 'liberty' would be:
'lirty'
'banana' would be changed into 'ban'.
'caramel' becomes 'came'.
Is there a basic and simple way to acheive this?
Thanks in advance for any help!
Kind Regards
///Magnus
Basic idea on how to solve this:
There are 2 cases. First letter a vowel or not a vowel.
This means we need the following structure
if(isVowel(firstLetter)){
//handle case with first letter a vowel
}else{
//handle other case
}
Since we want to print the first letter independent of the cases we can do that before the if, so that's done.
Then in both cases you can just call the function recursively.
So for the vowel case take the substring from 3 till the end.
str.subString(3, str.length()-1);
And finally don't forget about the edge cases: what would happen if you pass in an empty string?
Or if the first is a vowel but there's only 1 letter after?
This results in the following implementation:
public void printSpecial(String str){
if(str==null || str.isEmpty()){
return; //No letters to print
}
char firstLetter = str.charAt(0);
System.out.print(firstLetter); //print the current letter
if(isVowel(firstLetter)){
if(str.length()<4){
return; //Not enough letters to continue
}
printSpecial(str.substring(3, str.length()-1));
} else {
if(str.length()==1){
return; //Last letter done
}
printSpecial(str.substring(1, str.length()-1));
}
}
So the only thing left to do is implement the method
public boolean isVowel(char letter){
}
But I'll leave this up to you :)
public static void main(String[] args) {
String str = "caramel";
StringBuilder sb = new StringBuilder();
sb.append(str);
System.out.println("Before deletion=" + sb);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == 'a' || sb.charAt(i) == 'e' || sb.charAt(i) == 'i' || sb.charAt(i) == 'o' || sb.charAt(i) == 'u') {
if(i==sb.length()-2)
{//prevent index out of bounds
sb.deleteCharAt(i+1);
}
else if(i==sb.length()-1)
{
//prevent index out of bounds
}
else
{ //delete 2 charaters
sb.deleteCharAt(i+1);
sb.deleteCharAt(i+1);
}
}
}
System.out.println("After deletion=" + sb);
}
import java.util.Scanner;
import java.util.Stack;
public class Stack_1 {
public static void main(String[] args) {
String val;
Scanner input = new Scanner(System.in);
System.out.println("Enter Text: ");
val = input.nextLine();
push(val);
}
public static void push(String str) {
Stack<Character> stk = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
stk.push(str.charAt(i));
}
System.out.println(stk);
String reverseString = "";
String original = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverseString = reverseString + original.toUpperCase().charAt(i);
if (original.toUpperCase().equals(stk))
System.out.println("The string is a palindrome.");
else if (reverseString.toUpperCase().equals(stk))
System.out.println("The string is not a palindrome.");
}
}
Can anyone help me out. I didn't know where I went wrong. The question was to create a stack (Character), and display the text where it is a palindrome or not. The user had to enter input.
P.S This was one of my lab test.
If I followed the code correctly, the problem appears to be that the OP is comparing a String object (either original or reverseString) to Stack<Character> object.
So, the probable failure is the incorrect attempted comparison of a String object to a Stack object.
I think there is a 2nd failure in the if/else if logic given that an example input of "cool" is not a palindrome, but no output is produced in such a case.
EDIT: while the OP code does attempt to adjust for the case of the entered data (not given in the question as to whether that is a requirement or not), it does not account for spaces or other punctuation. According to the entry on Wikipedia about Palindromes, punctuation is also usually ignored. Again, whether being concerned about spaces, periods, dashes, etc. was part of the exercise is not defined in the question. The question is a bit under specified in terms of full requirements.
I would think a solution using a stack would take a String, push it by character to a Stack (probably correcting for case and stripping out all punctuation at that time), and then do a comparison by popping from the Stack. I think the OP code is missing part of the requirement in using a Stack.
Example code to have only characters on the Stack. There are other approaches, of course:
// push by character onto the stack; use only
// characters, and convert to lower case
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ) {
stk.push(Character.toLowerCase(c));
}
}
Example to remove all non characters from a check String:
// convert out comparison String to lower case and remove
// all non letters
String chk = str.toLowerCase().replaceAll("[^a-z]", "");
Example loop to use the Stack to check against the String:
// assume we have a palindrome
boolean palindrome = true;
// counter across the String
int i = 0;
// loop while there is more on the stack and we haven't
// failed our test
while (! stk.isEmpty() && palindrome) {
Character c = stk.pop();
palindrome = (c == chk.charAt(i++));
}
Sample Test Data:
cool is a palindrome: false
mom is a palindrome: true
Never odd or even is a palindrome: true
A man, a plan, a canal - Panama! is a palindrome: true
I am new to Java and trying to finish a program that will read a statement by the user and and scan to see if the amount of LEFT parenthesis match the RIGHT. The person who started the program created a stack but never made any use of it so I left it alone since I'm not very good with stacks. However, I was able to create a loop to to go through every character in the String to find the parenthesis, compare them, then print out if they are even or not. However I am having trouble with the while loop that goes through the String to find all parentheses. It's not working for some reason and I don't understand why. Any explanation on how to make this work will be greatly appreciated.
import java.util.*
public class ParenMatch
{
public static void main (String[] args)
{
Stack s = new Stack();
String line; // the string of characters to be checked
Scanner scan = new Scanner(System.in);
System.out.println ("\nParenthesis Matching");
System.out.print ("Enter a parenthesized expression: ");
line = scan.nextLine();
char parenline[] = new char[line.length()];
int x;
while(x < parenline.length) {
parenline[x] = line.charAt(x);
x++;
}
int l,r,i,morel,morer = 0;
while (i > parenline.length) {
if (parenline[i] == "(" )
l++;
if (line.charAt(i) == ")")
r++;
i++;
}
if (l > r) {
morel = l-r;
System.out.println("There are " +morel+ " more left parentheses than right");
}
if (r > l) {
morer = r-l;
System.out.println("There are " +morer+ " more right parentheses then left");
}
if (r == l) {
System.out.println("The amount of left and right parentheses are even.");
}
}
}
You need to initialize x so for example.
int x = 0;
You cannot increment an uninitialized variable.
Also to define parenline instead of looping and adding the char at the locations in the string just using one of the strings native methods:
char parenline[] = line.toCharArray();
Sorry if i explained this badly.
You had following mistakes:
not initializing
using double quote instead of single quote
checking whether i is greather than parenline.length
This is the correct code block:
int x=0;
...
int l,r,i,morel,morer;
l=r=i=morel=morer= 0;
while (i < parenline.length) {
if (parenline[i] == '(' )
l++;
if (line.charAt(i) == ')')
r++;
i++;
}
I made some changes to your code, it works fine.
However, the approach using Stack is better because allows you not only see if the amout of parenthesis is equal, but to see if the expression is correct. For example, if you have something like that: (x+y))+(x-(y+x) then your program can't tell that this is an incorrect expression because the amount of opening and closing parenthesis is equal.
import java.util.*;
public class Stackpr {
public static void main (String[] args)
{
String line; // the string of characters to be checked
Scanner scan = new Scanner(System.in);
System.out.println ("\nParenthesis Matching");
System.out.print ("Enter a parenthesized expression: ");
line = scan.nextLine();
int l = 0;
int r = 0;
for (int i = 0; i < line.length(); i++){
if (line.charAt(i) == '(')
l++;
else if (line.charAt(i) == ')')
r++;
}
if (l > r)
System.out.println("There are " + (l-r) + " more left parentheses than right");
else if (l < r)
System.out.println("There are " + (r - l)+ " more right parentheses then left");
else
System.out.println("The amount of left and right parentheses are even.");
}
}