So far I've been trying to write a program that's supposed to translate an English sentence to a language similar to pig Latin. Here's what the question looks like.
You will write a translator English to DrA’s TwinSpeak. Twins often make up a language that others can’t understand. It’s a secret code. It’s sort of like Pig Latin, but all twins make up their own rules.
A word that starts with a vowel has "-eh" added to the end.
Egg becomes egg-eh, open becomes open-eh, ultimate becomes ultimate-eh.
A word that starts with a single consonant, will have the consonant moved to the end of the word, then add the ‘eh’ word becomes ord-weh, mainly becomes ainly-meh
A word that starts with 2 or 3 consonants does not get changed at all.
Spain remains Spain. Three remains three.
and this is what I'm supposed to translate:
The rain in Spain stays mainly on the plain but the ants in France stay mainly on the plants
this is supposed to become like this:
The ain-reh in-eh Spain stays ainly-meh on-eh the plain ut-beh the ants-eh in-eh France stay ainly-meh on-eh the plants
I've written the code, however, it only seems to translate one word at a time rather than the whole sentence. if i translate the whole sentence, i get an error message.
import java.util.Scanner;
public class PartD {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a phrase to convert: ");
String phrase = keyboard.nextLine();
String[] words = phrase.split(" ");
for(int i = 0; i < words.length; i++ ) {
char firstLetter = (words[i].charAt(0));
if (firstLetter == 'a' || firstLetter == 'e' || firstLetter == 'i' || firstLetter == 'o' || firstLetter == 'u') {
String vowel = words[i] +"-eh";
System.out.print(vowel);
} else {
String start = words[i].substring(0,1);
String end = words[i].substring(1,phrase.length());
System.out.print(end + "-" + start + "eh" );
}
}
System.out.println( );
}
}
This line:
String end = words[i].substring(1,phrase.length());
is using the length of the entire initial string.
You want the length of the word you parsed, eg
String end = words[i].substring(1,words[i].length());
Also, add a space to each word you create to break up the result, eg
String vowel = words[i] +"-eh "; // note the added space
Related
I am writing a hangman program and one of the requirements to a hangman game is preventing the user from entering the same letter twice.
I have written the code for that, but the problem is every time I enter a letter it says it is already entered. I need to only say it when it is entered the second time. You guys have any suggestions? I've been trying to fix this for the past few hours, I figured I could ask on here to find some help. I already looked at another Stackoverflow question regarding something similar to this but all those solutions have the same result.
In Java, how can I determine if a char array contains a particular character?
I've tried something like this but it won't work either:
boolean contains = false;
for (char c : store) {
if (c == character) {
System.out.println("Already Entered");
contains = true;
break;
}
}
if (contains) {
// loop to top
continue;
}
SECOND CLASS-
public void hangman(String word, int life) {
KeyboardReader reader = new KeyboardReader();
char[] letter = new char[word.length()];
char[] store = new char[word.length()];
String guess;
int i = 0, tries = 0, incorrect = 0, count = 1, v = 0;
while (i < word.length()) {
letter[i] = '-';
I would just use the String.contains() method:
String aString = "abc";
char aChar = 'a';
return aString.contains(aChar + "");
To keep track of guessed letters you can use a StringBuffer, appending them using a StringBuffer.append() to append new letters (maintaining state) and use the StringBuffer.toString() method to get the String representation when you need to do the comparison above.
Since Java 1.5 the class String contains the method contains(). My idea is to collect all entered letters into a string variable and using above method:
// My code line
String letterAlreadyEntered = "";
// Your code line
char character = reader.readLine().charAt(0);
// My code line
if (letterAlreadyEntered.contains("" + character) == true) {
//Put code here what ever you want to do with existing letter
} else {
letterAlreadyEntered += character;
}
In my opinion, this is an easier way to check for occurrences than in arrays, where you have to write your own check method.
I'm working on a project for my Programming Applications course with WGU. I've decided to adapt a python-based pig latin converter from the previous course. I've almost got it done, but when I run the program, I get an extra word. For example, if I enter Latin, it prints atinLay, then on the next line, prints inLatay.
I'm not sure which part of the code is causing this. I know it should be a simple fix but I just can't find it. Here is my code:
import java.util.Scanner;
public class PigConverter
{
public static void main(String[] args)
{
Scanner anscay = new Scanner(System.in);
System.out.print("Enter a word:");
String word = anscay.nextLine();
System.out.println("This word, in pig latin, would be:");
String pigConvert;
for (int i=0; i < word.length(); i++)
{
if(word.charAt(i)=='a' || word.charAt(i)=='e' || word.charAt(i)=='i' ||
word.charAt(i)=='o' || word.charAt(i)=='u')
{
String second = word.substring(0,i);
String first = word.substring(i,word.length());
System.out.println(first+second+"ay");
}
}
}
}
I think that your loop is finding BOTH vowels in the word, so it/s doing the output twice. I think that your loop should break once you find the first vowel.
I am trying to take user input and modify it so that I print the string without any vowels. I have been able to do this successfully with the following code.
Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.next();
String newString = word.replaceAll("[aeiouAEIOU]","1");
System.out.printf("%s", newString);
However, I am trying to get the same effect by using a loop without the above method, replaceAll(). I have tried one other time, but got mixed up in the logic and restarted. My latest attempt is below and I cannot understand why it will not run properly. I will enter a string and without any error message it will not print back anything. The only time I get it to work is when I give it single characters to find in the string using something like
if(letter.contains("a"))
If the condition is found true it will print back a string of a's, however, this does not work for any combination of characters, only single ones. My complete code is below.
import java.util.Scanner;
public class practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.next();
int i = 0;
while (i < word.length()){
String letter = word.substring(i, (i+1));
if(letter.contains("[bcdfghjklmnpqrstvwxyz]")){
System.out.printf("%s",letter);
}
i++;
}
}
}
I am simply trying to find a way to complete this program only using conditionals, loops, UI, and only the methods length(), contains() or indexOf(), charAt(), and substring(x,y). Thanks in advance for any help I hope I have provided enough information.
Here is some sample output:
Enter a word:
Jordan
After I entered the word the program stops.
One way would be to convert your string to an array of characters toCharArray() and then compared with a case and add a new chain StringBuilder
String word = in.next();
StringBuilder bul = new StringBuilder();
for (char arg : word.toLowerCase().toCharArray()) {
switch(arg)
{
case 'a': System.out.println("A");break;
case 'e': System.out.println("E");break;
case 'i': System.out.println("I");break;
case 'o': System.out.println("O");break;
case 'u': System.out.println("U");break;
default:
bul.append(arg);
}
}
System.out.println(bul); //String not Vowels
in your code might change why a selected character with subtring can never contain such a long string like that "[bcdfghjklmnpqrstvwxyz]"
if(letter.contains("[bcdfghjklmnpqrstvwxyz]")){...}
for
if("[bcdfghjklmnpqrstvwxyz]".contains(letter.toLowerCase())){...}
You can use Scanner.useDelimeter(Pattern pattern) with regex. The regexfor removing vowel is - [^aeiou]+
If you want to ignore case then use this pattern - (?i)[^aeiou]+ .
And finally try the following code snippet -
scanner.useDelimeter(Pattern.compile("[^aeiou]+"));
When you say,
if(letter.contains("bcdfghjklmnpqrstvwxyz"))
your code will check if letter has the exact sequence of letters bcdfghjklmnpqrstvwxyz
In other words, it won't not check if any of these letters individually exists in the String.
Instead, you could go like this:
for (int i = 0; i < word.length(); i++) {
String currentLetter = String.valueOf(word.charAt(i));
if (!currentLetter.matches("a|e|i|o|u"))
System.out.print(currentLetter);
}
other way of doing is
Scanner s = new Scanner(System.in);
System.out.print("Enter input String");
String input = s.next();
StringBuilder sb = new StringBuilder("");
for(char c : input.toLowerCase().toCharArray())
if( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ){}
else sb.append(c+"");'
System.out.println("Given input without vowels : "+sb);
So im new to coding and i am having some issues... My program is supposed to ask the user for input, and will need to assume that all the input is lowercase... and need to assume there are no extra spaces, and will need to assume it ends with a period. The program will then translate the text into pig latin... Just incase you need the rules for pig latin they are if the word beging with a vowel, add a dash and "way" to the end... Otherwise, add a dash move the first letter to the end, and add "ay"... Now i know my code can be better but i just want to get it running first and then change it if i need too. The issue i am having is that, my code prints all my text but it doesnt not change the individual word to pig latin. And the other text has to also be in pig latin, i have pasted the code below. So any help would be awesome... Thanks.
import java.util.Scanner;
public class PigLat{
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
String text, pigLatin;
char first;
System.out.print("Enter a line of text: ");
text= scanner.nextLine();
first = text.charAt(0);
if (first == 'a' || first == 'e' || first =='i'||
first == 'o' || first == 'u')
pigLatin = text + "-way";
else
pigLatin = text.substring(1) + "-" + text.charAt(0) + "ay";
System.out.println("Input : " + text);
System.out.print("Output: " + pigLatin);
}
}
My Output:
Enter a line of text: this is a test
Input : this is a test
Output: his is a test-tay
----jGRASP: operation complete.
Call every operation on each individual word. Use String[] arr = text.split(" ") and you'll get an array containing all the individual words. Then use a for loop, and do the pig latin stuff on each word. Finally, combine it all back into 1 string, and that's your pig latin string.
I'll go ahead and let you know that yes, this is homework. I have hit a brick wall in completing it however and desperately need help. I'm also pretty new to Java and am still learning the language.
Okay, I am trying to write a program that asks the user to enter a sentence with no spaces but have them capitalize the first letter of each word. The program should then add spaces between the words and have only the first word capitalized, the rest should start with a lowercase. I can get the space inserted between the words, but I cannot get the first letter of each word lower-cased. I have tried several different ways, and the latest one is giving me this error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 72
at java.lang.AbstractStringBuilder.setCharAt(Unknown Source)
at java.lang.StringBuilder.setCharAt(Unknown Source)
at renfroKristinCh9PC14.main(renfroKristinCh9PC14.java:45)
I'm posting up my code and any and all help you can give me will be very much appreciated.
Thanks.
/*
This program will ask the user to enter a sentence without whitespaces, but
with the first letter of each word capitilized. It will then separate the words
and have only the first word of the sentence capitalized.
*/
import java.util.*;
public class renfroKristinCh9PC14
{
public static void main(String[] args)
{
//a string variable to hold the user's input and a variable to hold the modified sentence
String input = "";
//variable to hold a character
char index;
//create an instance of the scanner class for input
Scanner keyboard = new Scanner(System.in);
//welcome the user and explain the program
userWelcome();
//get the sentence from the user
System.out.println("\n Please enter a sentence without spaces but with the\n");
System.out.println(" first letter of each word capitalized.\n");
System.out.print(" Example: BatmanIsTheBestSuperheroEver! ");
input = keyboard.nextLine();
//create an instance of the StringBuilder class
StringBuilder sentence = new StringBuilder(input);
//add spaces between the words
for(int i=0; i < sentence.length(); i++)
{
index = sentence.charAt(i);
if(i != 0 && Character.isUpperCase(index))
{
sentence.setCharAt(index, Character.toLowerCase(index));
sentence.append(' ');
}
sentence.append(index);
}
//show the new sentence to the user
System.out.println("\n\n Your sentence is now: "+sentence);
}
/*********************************************************************************** *************************
************************************************************************************ *************************
This function welcomes the user and exlains the program
*/
public static void userWelcome()
{
System.out.println("\n\n **************** ****************************************************\n");
System.out.println(" * Welcome to the Word Seperator Program *");
System.out.println(" * This application will ask you to enter a sentence without *");
System.out.println(" * spaces but with each word capitalized, and will then alter the *");
System.out.println(" * sentence so that there arespaces between each word and *");
System.out.println(" * only the first word of the sentence is capitalized *");
System.out.println("\n ********************************************************************\n");
}
}
You are appending to the same string that you are iterating through. Instead, just make your sentence an empty StringBuilder. Then you can append to that while iterating through input. For example:
StringBuilder sentence = new StringBuilder();
//add spaces between the words
for(int i=0; i < input.length(); i++)
{
char letter = input.charAt(i);
if(i != 0 && Character.isUpperCase(letter))
{
sentence.append(' ');
sentence.append(Character.toLowerCase(letter));
}
else
{
sentence.append(letter);
}
}
(Note that I've changed the variable name from index to letter, which is a lot less confusing.)
You have a few different problems here. The main one is that when you call
sentence.setCharAt(index, Character.toLowerCase(index));
you're passing in the actual character in as the first argument, instead of the position. You see, you've just done
index = sentence.charAt(i);
so index is the character itself. Java implicitly converts this character to an integer - but it's not the integer that you want it to be. You probably should have written
sentence.setCharAt(i, Character.toLowerCase(index));
instead.
Also, your sentence.append(' '); will append the space to the end of the StringBuilder, rather than inserting it where you want it to.
And your final sentence.append(index); will duplicate the character. I really don't think you want to do this.