Replace character/characters after a specific character in a String, Java - java

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

Related

Easy JAVA questions. But hard for me

When the first character of word starts with 'A' or 'a', let the program output the word 'America'. if the first character of the word starts with other characters, let the program prints "error"
public class Home1 {
public static void main(String[] args) {
String str=args[0];
char ch;
ch= (1) . (2) ;
if( (3) ) System.out.println("America");
(4) System.out.println("Error");
}
}
I have figured out that 4th one is 'else'
3rd one may be something like, 'first character = 'a','A'
but i do not fully get them.
could you help me?
(1) and (2): get somehow the char at position 0 of the string read. Documentation of the available methods on Strings is available here: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
(3) Compare the character read with 'A' and 'a':
If char equals 'A' or char equals 'a'....
Documentation can be found here: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html
Ok this looks like a code fill in the blanks,
Your actual code should be something like this,
public static void main(String[] args) {
String str = args[0];
char ch;
ch = str.charAt(0);
if (ch == 'a' || ch == 'A')
System.out.println("America");
else
System.out.println("Error");
}
So,
(1) = str
(2) = charAt(0)
(3) = ch == 'a' || ch == 'A'
(4) = else
Hope this helps.

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.

How do I use hasNext() along with Scanner in a while loop in Java?

I have only a few weeks of experience in Java and I'm having trouble with an assignment I was given in my Intro to Java class. The assignment is write a program that allows the user to input a letter and determines whether the letter is a vowel or a consonant. The code I wrote for that works fine, but when I try to add in a while loop so the user can enter as many letters as they'd like, the program no longer works. My professor says the loop should continue until reaching EOF, and I followed the outline he gave but I'm still having trouble. This is the entire code:
import java.util.Scanner;
public class Vowel
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
String w;
while(in.hasNext())
{
w = in.next();
System.out.print("Enter a letter: ");
char letter = in.nextLine().charAt(0);
int ascii;
ascii =((int) letter);
Boolean valid = true;
if (ascii < 65 || ((ascii > 90) && (ascii < 97)) || ascii > 122)
{
System.out.println(letter + " is an invalid input");
valid = false;
}
else if(valid)
{
System.out.print(letter + " is a ");
switch (ascii)
{
case 'a' :
case 'A' : System.out.println("vowel");
break;
case 'e' :
case 'E' : System.out.println("vowel");
break;
case 'i' :
case 'I' : System.out.println("vowel");
break;
case 'o' :
case 'O' : System.out.println("vowel");
break;
case 'u' :
case 'U' : System.out.println("vowel");
break;
default : System.out.println("consonant");
}
}
}
}
}
When I run the code as is, the console just stays blank and if I type anything in (just trying to get it to do something), I get an error that says "Exception in thread "main" java.lang.StringOutOfBoundsException: String index out of range: 0."
The code works without the while loop and it also works with a while loop using a counter, so I know my mistake has something to do with the hasNext(). If anyone could point me in the right direction, it would be greatly appreciated! Thank you :)
You are ignoring w and reading another line, but you haven't checked that there is a line to read or that the line you read isn't empty. You could do so with something like
if (in.hasNextLine()) { // <-- check if there is a line.
String line = in.nextLine(); // <-- read the line.
if (!line.isEmpty()) { // <-- make sure there is at least one character.
char letter = line.charAt(0); // <-- get the first character.

Could anyone help me with why my Java method isn't quite doing what I'm expecting it to do?

For a class project, we have to create a hangman game in Java (we're starting off with object oriented programming, so this is getting us used to it) and I have the class file then the main file.
Everything's working great, but I want one of my methods in the class file to tell the player if they've already guessed a particular character.
Basically, the method uses a for loop to add the guessed characters into a character array, and every time the player guesses it checks to see if that character is there (if it is, it breaks out of the loop) and if not, and the index value is 0 (this means it's unwritten, right?) it will write the character that was guessed to that index value.
The only other thing that I don't think is self explanatory in the code, is that if the player has yet to make any guesses, it makes the first value the guess, so it has something to start with in the array.
Any help would be appreciated, and if anyone has any input on how to improve my code or whatever, I'd be happy to hear that as well. Thanks so much. :)
public void makeGuess(char c) {
boolean alreadyGuessed = false, anyMatches = false;
matches = 0;
guesses++;
if (guesses == 1) {
guessedChars[0] = c;
}
for (int i = 0; i < guessedChars.length; i++) { //it goes through it and will see that it was already guessed
if (guessedChars[i] == c) {
alreadyGuessed = true;
break;
}
else if (guessedChars[i] != c && guessedChars[i] == 0) {
guessedChars[i] = c;
}
}
if (alreadyGuessed == false) {
for (int i = 0; i < word.length; i++) {
if (word[i] == c) {
anyMatches = true;
matches++;
disguisedWord[i] = c;
}
}
}
if (anyMatches == true) {
System.out.println("You guessed correctly!");
System.out.println("There were " + matches + " matches.");
}
else if (alreadyGuessed == true) {
System.out.println("You already guessed this letter, derp.");
}
else {
System.out.println("Sorry, that character is not in the word to be guessed.");
wrongGuesses++;
}
// for (int i = 0; i < guessedChars.length; i++) {
// System.out.print(guessedChars[i] + " ");
// }
}
MAIN METHOD:
import java.util.Scanner;
class HangmanDemo {
public static void main(String[] args) {
//Object initialization
Scanner keyboard = new Scanner(System.in);
Hangman word = new Hangman("jordan");
//Variable declaration
char letterGuess;
int limit;
//Interact with user
System.out.print("What would you like the limit of guesses to be: ");
limit = keyboard.nextInt();
//BEGIN ZE GAME
while (word.isFound() == false && word.getWrongGuessCount() <= limit) {
System.out.println();
System.out.print("Letter guess: ");
letterGuess = keyboard.next().charAt(0);
word.makeGuess(letterGuess);
System.out.println(word.getDisguisedWord());
}
if (word.getGuessCount() == limit) {
System.out.println("\nSorry, too many guesses.");
}
else {
System.out.println("\nCongratulations! You succesfully solved the word!");
}
}
}
So, check this out:
First time you call the method, both alreadyGuessed and and anyMatches will stay false... and that's obviously not good.
Second: OOP is NOT procedural P. More concretely: a method is not supposed to do as many things as you do. A method should have a lot of explaining to do it if plans to be larger than 10 lines. That's so full of language constructs you can't go over it fast. Split your code... less local variables, more methods.
Hope that helps.
One way to keep track of guesses would be to use either a boolean or char array (to correspond to the cardinal letter guessed; a=0, b=1, etc).
The main problem I'm seeing is in your looping logic.
This will always be true the first time because guessedChars[0] will be equal to the first entry added and you add the first entry before checking if a letter was guessed.
if (guessedChars[i] == c) {
alreadyGuessed = true;
break;
}
Also, you don't tell us how guessedChars[] is defined. Depending on how you did this you might have problems with the whole thing given that the loop is driven off of guessedChars.length and assuming that an unassigned value would be 0. The big thing I notice is that you don't break after you have determined that the letter has not yet been guessed. You at a minimum need to do this otherwise all other elements after guessedChars[i] will also be set to that guessed letter. I do recommend perhaps using a different type of loop though.
bool searchingForLetter = true;
do
{
//.... Your Logic
//.... searchingForLetter = false when you have either found the letter
//.... or placed the letter in the array
//.... or reached the end of the array
} while(searchingForLetter)
One possible solution is to use the integer value of an char, because every letter is represented by a number. For the ANSI-Standard it is useful to know, that the common letters starting a number 65 for 'A' up to 90 for 'Z'. From 97 up to 122 you will find the small letters.
You need a boolean array of 25, every value stand for one letter. Here is some code to demonstrate the functionality:
boolean[] guessedChars = new boolean[25];
char[] test = "HELLO".toCharArray();
for (char element : test) {
System.out.println(element);
System.out.println((int) element);
if (guessedChars[element - 65] == false) {
guessedChars[element - 65] = true;
} else {
System.out.println("You already guessed this letter, derp.");
}
}
'Hello' is the example string, to get the right position in the array you have to substract 66 from the element integer value. An 'A' with the value of 65 will be stored in guessedChars[0]. It is easy to extend for small letters for the hangman game, because you can changed the String to upper case with the toUpperCase()-method before checking.

Palindrome tester with Java, ignoring spaces and punctuation

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.

Categories

Resources