Creating an Ubbi Dubbi translator in Java - java

I'm in an entry java class, and for one of my programs I am expected to create a ubbi dubbi translator, which ads a ub before every vowel and vowel cluster. I cannot figure out how to get my program to run correctly, and also am unsure how to make it exclude the extra vowel included with the cluster. I am not allowed to use Stringbuilder..
public void buttonPressed()
{
String lowerCase = "";
String userInput = input.getText();
Scanner words = new Scanner( userInput );
String ubbiDubbi = "";
//Splits up user input by line
while (words.hasNext()) {
//Converting to lower case.
lowerCase = words.next().toLowerCase();
System.out.println(lowerCase);
}
for (int i = 0; i < lowerCase.length(); i++) {
if (lowerCase.charAt(i+1) == 'a'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'e') {
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'i'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'o'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'u') {
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else {
ubbiDubbi += lowerCase.charAt(i);
}

To get this translator to work you basically just need to step through each character in the input and write it to the output. In addition if the input is a vowel you need to write "ub" out first, except where the previous character was also a vowel.
One thing which is going to be handy is to be able to identify vowels. Starting by writing a function for this is a good idea. It could look like:
private boolean isVowel(char c) {
return
c == 'a' || c == 'A' ||
c == 'e' || c == 'E' ||
c == 'i' || c == 'I' ||
c == 'o' || c == 'O' ||
c == 'u' || c == 'U';
}
Now that's in place if you look at the translation, we want to step over every character in the input and write it to the output. This could look like this:
private String translate(String raw) {
String translated = "";
for(char c:raw.toCharArray()) {
// some extra stuff needed here
translated += c;
}
return translated;
}
For the extra stuff you need to know if the current character is a vowel and whether the previous character was a vowel so we can add a little to do this:
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false; //
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
And finally to ad "ub" where required you can check if the character is a vowel and whether the last character was a vowel:
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false;
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
if(!wasLastCharacterVowel) {
translated += "ub";
}
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
With that in place you just need to hook up the button press action etc. So it might look a little like this:
public class UbbiDubbi {
private boolean isVowel(char c) {
return
c == 'a' || c == 'A' ||
c == 'e' || c == 'E' ||
c == 'i' || c == 'I' ||
c == 'o' || c == 'O' ||
c == 'u' || c == 'U';
}
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false;
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
if(!wasLastCharacterVowel) {
translated += "ub";
}
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
public void buttonPressed() {
String userInput = "";// = input.getText();
Scanner words = new Scanner( userInput );
while (words.hasNext()) {
String lowerCase = words.next().toLowerCase();
String translated = translate(lowerCase);
System.out.println(translated);
}
words.close();
}
public static void main(String...none) {
System.out.println(new UbbiDubbi().translate("The quick brown fox jumps over the lazy aadvark"));
}
}
adding the main method gives an easy way to test out the translation. Hope this helps.

Related

How do I handle punctuation in this Pig Latin translator?

The rest of the code is working perfectly but I cannot figure out how to prevent punctuation from being translated.
public class PigLatintranslator
{
public static String translateWord (String word)
{
String lowerCaseWord = word.toLowerCase ();
int pos = -1;
char ch;
for (int i = 0 ; i < lowerCaseWord.length () ; i++)
{
ch = lowerCaseWord.charAt (i);
if (isVowel (ch))
{
pos = i;
break;
}
}
if (pos == 0 && lowerCaseWord.length () != 1) //translates if word starts with vowel
{
return lowerCaseWord + "way"; // Adding "way" to the end of string
}
else if (lowerCaseWord.length () == 1) //Ignores words that are only 1 character
{
return lowerCaseWord;
}
else if (lowerCaseWord.charAt(0) == 'q' && lowerCaseWord.charAt(1) == 'u')//words that start with qu
{
String a = lowerCaseWord.substring (2);
return a + "qu" + "ay";
}
else
{
String a = lowerCaseWord.substring (1);
String b = lowerCaseWord.substring (0,1);
return a + b + "ay"; // Adding "ay" at the end of the extracted words after joining them.
}
}
public static boolean isVowel (char ch) checks for vowel
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
{
return true;
}
return false;
}
}
I need the translation to ignore punctuation. For example "Question?" should be translated to "estionquay?" (question mark still in the same position and not translated)
As Andreas said, if the function is expecting only one word, it should be the responsibility of the calling function to ensure there's no full sentence or punctuation being passed to it. With that said, if you require the translator to handle this, you need to find the index of the string where the punctuation or non-letter character occurs. I added in a main method to test the function:
public static void main(String[] args) {
System.out.println(translateWord("QUESTION?"));
}
I added a loop into the qu case to find the punctuation being input, the two checks are to see if the character at position i is inside the range of a - z. The sub-string then only goes to the point where the punctuation is found.
int i;
for (i = 0; i < lowerCaseWord.length(); i++) {
if(lowerCaseWord.charAt(i) > 'z' || lowerCaseWord.charAt(i) < 'a') {
break;
}
}
String a = lowerCaseWord.substring (2, i);
String b = lowerCaseWord.substring(i);
return a + "qu" + "ay" + b;
This may need some tweaking if you're worried about words with hyphens and whatnot but this should put across the basic idea.
Here's the output I received:
$javac PigLatintranslator.java
$java -Xmx128M -Xms16M PigLatintranslator
estionquay?

My Java program on Eclipse stopped printing out to the console but it was working correctly before

I'm working on a Pig Latin translator for a class. I had my program working before; it was printing out in the bottom for loop from the translatedWords array list. But the latest version does not print in the bottom for loop. I suspect it's a curly bracket but I can't seem to find it.
package stringTest;
import java.util.ArrayList;
public class StringTest {
public static void main(String[] args) {
String userString = "THIS IS A STRING";
// We might need to trim the string first it throws an error if theres
// white space around word
// Making string lowercase, first
userString = userString.toLowerCase();
// Splitting up string into individual words
String[] stringArray = userString.split(" ");
ArrayList<String> translatedWords = new ArrayList<String>();
// going through each string with foreach loop
for (String ss : stringArray) {
System.out.println("prints here in intial for loop");
// pulling out the words that start with a vowel
// since they just get "way" at the end
if (ss.charAt(0) == 'a' || ss.charAt(0) == 'e'
|| ss.charAt(0) == 'i' || ss.charAt(0) == 'o'
|| ss.charAt(0) == 'u') {
ss = ss.concat("way");
translatedWords.add(ss);
}
// If the words don't start with a vowel
// trying to figure out how to cut them at first vowel and
// concatenate to end
else {
for (int i = 0; i < ss.length();) {
if (ss.charAt(i) == 'a' || ss.charAt(i) == 'e'
|| ss.charAt(i) == 'i' || ss.charAt(i) == 'o'
|| ss.charAt(i) == 'u') {
ss = ss.substring(i, ss.length());
String sss = ss.substring(0, i + 1);
String ss44 = ss.substring(i + 1);
String ss33 = ss44 + sss;
ss33 = ss33 + "ay";
translatedWords.add(ss33);
System.out.println(ss33);
System.out.println("Why won't this print");
break;
}
}
}
for (String fs : translatedWords) {
System.out.print(fs.toString() + " ");
}
}
}
}
It's not a curly bracket but the for loop is running infinitely
The i is never incremented in for statement or inside the for
So the if condition will keep on running for the first character of the string ,if it is not a vowel which will be false for the string 'this', so it will never get inside the if statement
//for (int i = 0; i < ss.length();) {//no i++ implemented
for (int i = 0; i < ss.length();i++) {
if (ss.charAt(i) == 'a' || ss.charAt(i) == 'e'
|| ss.charAt(i) == 'i' || ss.charAt(i) == 'o'
|| ss.charAt(i) == 'u') {
ss = ss.substring(i, ss.length());
String sss = ss.substring(0, i + 1);
String ss44 = ss.substring(i + 1);
String ss33 = ss44 + sss;
ss33 = ss33 + "ay";
translatedWords.add(ss33);
System.out.println(ss33);
System.out.println("Why won't this print");
break;
}
}

Phone numbers in java

I've got the code to put a seven letter phrase into a phone number. The hyphen is not returning in the correct spot. I really don't know how to fix this problem. It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Code:
import java.util.*;
import java.lang.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if (letter== 'A' || letter=='a' || letter== 'B' || letter=='b' || letter=='C' || letter=='c') {
return '2';
}
else if (letter== 'D' || letter=='d' || letter== 'E' || letter=='e' || letter=='F' || letter=='f') {
return '3';
}
else if (letter== 'G' || letter=='g' || letter== 'H' || letter=='h' || letter=='I' || letter=='i') {
return '4';
}
else if (letter== 'J' || letter=='j' || letter== 'K' || letter=='k' || letter=='L' || letter=='l') {
return '5';
}
else if (letter== 'M' || letter=='m' || letter== 'N' || letter=='n' || letter=='O' || letter=='o') {
return '6';
}
else if (letter== 'P' || letter=='p' || letter== 'Q' || letter=='q' || letter=='R' || letter=='r'|| letter=='S' || letter=='s') {
return '7';
}
else if (letter== 'T' || letter=='t' || letter== 'U' || letter=='u' || letter=='V' || letter=='v') {
return '8';
}
else if (letter== 'W' || letter=='w' || letter== 'X' || letter=='x' || letter=='Y' || letter=='y' || letter=='Z' || letter=='z') {
return '9';
}
if (letter == ' ')
return '-';
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a 7 letter phrase: ");
String number = input.nextLine();
for (int i = 0; i < 8; i++) {
System.out.print(getNumber(number.toUpperCase().charAt(i)));
}
}
}
It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Here you go! A bit of regex is always good for the soul:
{
String number = input.nextLine();
final StringBuilder builder = new StringBuilder(); // Buffer the sequence.
for (int i = 0; i < 8; i++) {
builder.append(getNumber(number.toUpperCase().charAt(i)));
if (builder.toString().getCharAt(2) != '-') // If the format isn't correct, fix it
System.out.println(builder.toString().replaceFirst("(...)(.).(...)", "$1-$2$3"))
}
}
As seen from CSáµ 's comment, you can use the following universal regex instead, such that the section becomes:
builder.toString().replaceFirst("^\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*$", "$1$2$3-$4$5$6$7");
Edit: Updated regex as \N backreferences does not work in Java.
Here's a quick and dirty solution to your problem.
import java.util.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if( letter < 'A' )
{
ret = '0';
}
else if( letter < 'D' )
{
ret = '2';
}
else if( letter < 'G' )
{
ret = '3';
}
else if( letter < 'J' )
{
ret = '4';
}
else if( letter < 'M' )
{
ret = '5';
}
else if( letter < 'P' )
{
ret = '6';
}
else if( letter < 'T' )
{
ret = '7';
}
else if( letter < 'W' )
{
ret = '8';
}
else if( letter <= 'Z' )
{
ret = '9';
}
else
{
ret = '0';
}
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println( "Please enter a 7 letter phrase: " );
String number = input.nextLine().toUpperCase();
StringBuffer buff = new StringBuffer();
for( int i = 0, j = 0; j < number.length() && i < 7; j++ )
{
char c = number.charAt(j);
if( c != ' ' )
{
if( i == 3 )
{
buff.append( '-' );
}
buff.append( getNumber( c ) );
i++;
}
}
System.out.println( buff );
}
}
Key points:
There is no need to check for lower case if the alpha characters are guaranteed to be uppercase.
There is no need to uppercase the input string on each iteration of the loop. Do it once at the beginning.
I'm ignoring spaces, and always adding a hyphen before I print position 3 (ie the fourth character).
chars can be compared just like numbers, using ranges. This simplifies the amount of code quite a bit (ie. each letter within a range doesn't need to be written down).

Pig Latin Translate (Sentence)

I am making a Pig Latin translator and I don't really knwo where to go from here. I have the basic code, but I need to revise it in order for it to translate a whole sentence. If anyone can tell me how to use my String[] words I would really appreciate it. Thanks a lot!
import java.io.*;
import java.util.*;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
System.out.print("Please enter a phrase to translate: ");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
String[] words = str.split("\\s+");
String answer = "";
if (str.startsWith("a") || str.startsWith("e") || str.startsWith("i") || str.startsWith("o") || str.startsWith("u"))
{
System.out.print(str + "way");
}
else
{
answer = str.substring(2,str.length());
String answer2 = str.substring(1,str.length());
String answer3 = str.substring(3,str.length());
String answer4 = str.substring(4,str.length());
String d = str.substring(0,4);
if (!(d.contains("a") || d.contains("e") || d.contains("i") || d.contains("o") || d.contains("u")))
{
System.out.print(answer4 + d + "ay");
}
else
{
String c = str.substring(0,3);
if (!(c.contains("a") || c.contains("e") || c.contains("i") || c.contains("o") || c.contains("u")))
{
System.out.print(answer3 + c + "ay");
}
else
{
String b = str.substring(0,2);
if (!(b.contains("a") || b.contains("e") || b.contains("i") || b.contains("o") || b.contains("u")))
{
System.out.print(answer + b + "ay");
}
else
{
String a = str.substring(0,1);
if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
System.out.print(answer2 + a + "ay");
}
}
}
}
}
}
}
This should translate each word in that array, just use a for loop around your whole if block
for(String word: words) {
//put your whole if block here
//word is the variable to translate (i.e. word.startsWith("a"))
}
alternatively for beginners:
for(int i = 0; i < words.length(); i++) {
//put if statements here
//words[i] is the variable to translate (i.e. words[i].startsWith("a"))
}
You will also need to change all str references inside the loop to word[i], since that is the variable you want to use.
You can have a for loop that goes through each word, and apply your logic to each word:
for(String str : words ) {
if (str.startsWith("a") || str.startsWith("e") || str.startsWith("i") || str.startsWith("o") || str.startsWith("u"))
{
System.out.print(str + "way");
}
else
{
answer = str.substring(2,str.length());
String answer2 = str.substring(1,str.length());
String answer3 = str.substring(3,str.length());
String answer4 = str.substring(4,str.length());
String d = str.substring(0,4);
if (!(d.contains("a") || d.contains("e") || d.contains("i") || d.contains("o") || d.contains("u")))
{
System.out.print(answer4 + d + "ay");
}
else
{
String c = str.substring(0,3);
if (!(c.contains("a") || c.contains("e") || c.contains("i") || c.contains("o") || c.contains("u")))
{
System.out.print(answer3 + c + "ay");
}
else
{
String b = str.substring(0,2);
if (!(b.contains("a") || b.contains("e") || b.contains("i") || b.contains("o") || b.contains("u")))
{
System.out.print(answer + b + "ay");
}
else
{
String a = str.substring(0,1);
if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
System.out.print(answer2 + a + "ay");
}
}
}
}
}
}
You can use an enhanced for loop around your if block to translate the entire array:
for(String word: words) {
/*
*if block goes here
*...
*/
}
Though creating a translator like this is rather unsafe (e.g. code injections), unless the input is put in from a trusted source.
If you are familiar with lexer/parsers you should look into using a generator such as ANTLR to create safer (albeight more complex) language translators.
#include stdio.h>
#include conio.h>
#include stdlib.h>
#include string.h>
void main()
{
char * sUserInput ;
char * check ;
char * firstletter;
char ch = NULL;
int i = 0 ;
int j = 0 ;
int k = 0 ;
int spacecount = 0 ;
int count = 0 ;
int count1 = 0 ;
int var = 0 ;
int gold = 1 ;
sUserInput = (char *) malloc(sizeof(char));
check = (char *) malloc(sizeof(char));
firstletter = (char *) malloc(4*sizeof(char));
printf("Enter the sentence \n");
while(ch != '\n')
{
scanf("%c",&ch);
sUserInput[i]=ch;
sUserInput = (char *) realloc(sUserInput,((i+2))*sizeof(char));
i++;
if( ch == ' ')
{
spacecount++;
}
}
while(sUserInput[j] != '\n')
{
count1++;
if(gold==1)
{
firstletter[var]=sUserInput[j];
firstletter[var+1]='a';
firstletter[var+2]='y';
gold=0;
j++;
}
if(sUserInput[j] !=' ')
{
check[k] = sUserInput[j];
check = (char *) realloc(check,((k+2))*sizeof(char));
printf("%c",check[k]);
k++;
}
if(sUserInput[j] ==' ' || (count1 == (i-(spacecount+2))))
{
for(count=0;count<3;count++)
{
printf("%c",firstletter[count]);
}
var=0;
gold=1;
printf(" ");
}
j++;
}
free(sUserInput);
free(check);
free(firstletter);
getch();
}

deleting same letter from input when writing to output java

I'd like some help with a problem I have in the following code.
package piglatin;
public class asdg {
public static void main(String[] args) {
String word = "fifteen";
int vowelSpot = findFirstVowelPosition(word);
String wordBeg = "";
String wordEnd = "ay";
String wordNew = "";
System.out.println(vowelSpot);
wordBeg = word.substring(0,vowelSpot-1);
System.out.println(wordBeg);
word = word.replace(wordBeg,"");
System.out.println(word);
wordNew = word + wordBeg + wordEnd;
System.out.println(wordNew);
}
public static int findFirstVowelPosition(String word)
{
int vowelPosition = -1;
word = word.trim();
for(int i=1; i <=word.length(); i++)
{
if ((word.charAt(i-1) == 'a') ||(word.charAt(i-1) == 'A')
||(word.charAt(i-1) == 'e') ||(word.charAt(i-1) == 'E')
||(word.charAt(i-1) == 'i') ||(word.charAt(i-1) == 'I')
||(word.charAt(i-1) == 'o') ||(word.charAt(i-1) == 'O')
||(word.charAt(i-1) == 'u') ||(word.charAt(i-1) == 'U')
||(word.charAt(i-1) == 'y') ||(word.charAt(i-1) == 'Y')){
vowelPosition = i;
return vowelPosition;
}
}
return vowelPosition;
}
}
The purpose of this code is to take the string Word and put it in piglatin. Word will start with a consonant. The problem I'm having is when the string contains a specific consonant, then the first vowel, and the same consonant, it'll get rid of the second consonant.
This specific code isn't for homework, however I'll be applying this to a homework assignment.
I've got it:
Replace this line:
word = word.replace(wordBeg,"");
with
word = word.replaceFirst(wordBeg,"");
Check the documentation on it: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

Categories

Resources