Pig Latin Translate (Sentence) - java

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

Related

How do I add a loop to this password checker

I have created a password checker program. All it does is ask for a password and then outputs if the password doesn't follow the rules I have made. I would like to get help to figure out to loop this right so you can check multiple passwords without restarting.
import java.util.Scanner;
public class password {
public static void main(String[] args) {
String end = "endofinput";
Scanner word = new Scanner(System.in);
System.out.print("Password:");
String password = word.nextLine();
// password
if(password.contains("password")){
System.out.println("Password may not contain the word password");
}
// lenght
if( password.length() < 8){
System.out.println("Needs to be longer");
}
//space/special check
if((password.contains(" ")||password.contains("#")|| password.contains("#")|| password.contains("!") || password.contains("~")|| password.contains("$") || password.contains("%") || password.contains("^")|| password.contains("*") || password.contains("(")|| password.contains(")") || password.contains("-")|| password.contains("+") || password.contains("/")|| password.contains(":") || password.contains("&")|| password.contains(".")|| password.contains(", ") || password.contains("<")|| password.contains(">")|| password.contains("?")|| password.contains("|"))){
System.out.println("No spaces or special Characters");
}
// Number
if(!(password.contains("1")|| password.contains("2")||password.contains("3")||password.contains("4")||password.contains("5")||password.contains("6")||
password.contains("7")||password.contains("8")||password.contains("9")||password.contains("0"))){
System.out.println("Need a Number");
}
// upper case
if (true) {
int count = 0;
for (int i = 65; i <= 90; i++) {
// type casting
char c = (char)i;
String e = Character.toString(c);
if (password.contains(e)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs an uppercase letter");
}
}
//lower case
if (true) {
int count = 0;
for (int i = 90; i <= 122; i++) {
// type casting
char c = (char)i;
String str1 = Character.toString(c);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs Lower case");
}
}
}
}
Just add a while with a "True" of condition, and put an if with a condition you want, to quit the loop, for example ìf(password == "Exit"). like this.
while(true)
{
System.out.print("Password:");
String password = word.nextLine();
if(password == "exit")
{
System.out.println("Ending the program");
break; //this break will stop the loop
}
// password
if(password.contains("password")){
System.out.println("Password may not contain the word password");
}
// lenght
if( password.length() < 8){
System.out.println("Needs to be longer");
}
//space/special check
if((password.contains(" ")||password.contains("#")|| password.contains("#")|| password.contains("!") || password.contains("~")|| password.contains("$") || password.contains("%") || password.contains("^")|| password.contains("*") || password.contains("(")|| password.contains(")") || password.contains("-")|| password.contains("+") || password.contains("/")|| password.contains(":") || password.contains("&")|| password.contains(".")|| password.contains(", ") || password.contains("<")|| password.contains(">")|| password.contains("?")|| password.contains("|"))){
System.out.println("No spaces or special Characters");
}
if(!(password.contains("1")|| password.contains("2")||password.contains("3")||password.contains("4")||password.contains("5")||password.contains("6")||
password.contains("7")||password.contains("8")||password.contains("9")||password.contains("0"))){
System.out.println("Need a Number");
}
// upper case
if (true) {
int count = 0;
for (int i = 65; i <= 90; i++) {
// type casting
char c = (char)i;
String e = Character.toString(c);
if (password.contains(e)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs an uppercase letter");
}
}
//lower case
if (true) {
int count = 0;
for (int i = 90; i <= 122; i++) {
// type casting
char c = (char)i;
String str1 = Character.toString(c);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs Lower case");
}
}
}

Creating an Ubbi Dubbi translator in 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.

IndexOutOfBound error with string manipulation

this is the code for a pig-latin translator in JAVA, it works with one word but never with a sentence. It seems that the code at line 30 is messing everything up, and I'm not sure how it is doing that or how I can fix it. IndexOutOfBoundError on line 8 and line 30. I'm not sure how to fix this, help.
public class Practice
{
public static void main(String[] args)
{
String a = "hello Stranger";
System.out.println(translate(a)); //8
}
private static String translate(String a)
{
String XD = a;
boolean repeat = true;
int first = 1;
int second = 0;
do
{
second = XD.indexOf(" ");
if (second == -1)
{
repeat = false;
XD = vowelFinder(a);
break;
}
else
{
XD = XD + vowelFinder(a.substring(first, second)); //30
}
first = second +1;
}while(repeat == true);
return XD;
}
private static boolean isVowel (char c)
{
if (c == 'a'|| c== 'e'|| c== 'i' || c == 'o' || c== 'u')
{
return true;
}
return false;
}
private static String vowelFinder(String s)
{
String nope = s;
for(int i = 0; i <= s.length(); i++)
{
if(isVowel(s.charAt(i)) == true)
{
nope = nope.substring(i) + "-"+nope.substring(0, i);`
return nope;
}
}
return nope;
}
}
Try this;
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
String yourSentence="";
do {
String[] words;
System.out.print("Enter your words here: ");
yourSentence = input.nextLine();
words = yourSentence.split(" ");
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
System.out.print(word + "way ");
else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
else
System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
}
System.out.println();
} while(!yourSentence.equals("quit"));
}
}

Postfix to Infix

I'm trying to convert a postfix into an infix. I have some code, but I'm not able to fix it. There may be a condition I am missing. Or my structure is not quite right.
Also since I am new to Java I may need some help with "Stack<Character>".
public static String postfixToInfix(String postfix) {
Stack<Character> stack = new Stack();
Stack<Character> backup = new Stack();
StringBuilder infix = new StringBuilder(postfix.length());
infix.append('(');
for (int i = 0; i < postfix.length(); i++) {
if (!isOperator(postfix.charAt(i))) {
stack.push(postfix.charAt(i));
} else {
if (stack.size() == 1 ) { //stack is 1
backup.push(postfix.charAt(i));
}
if (stack.size() == 0 && backup.size()%5 == 0) { //stack is 0
stack.push(backup.pop());
stack.push(backup.pop());
stack.push(backup.pop());
stack.push(backup.pop());
stack.push(backup.pop());
stack.push(postfix.charAt(i));
}
if (stack.size() >= 2) { //stack is > 1
char arg2 = stack.pop();
char arg1 = stack.pop();
backup.push(')');
backup.push(arg2);
backup.push(postfix.charAt(i));
backup.push(arg1);
backup.push('(');
}
}
}
while (!backup.empty()) { //only size 3
stack.push(backup.pop());
}
while (!stack.empty()) { //only size 3
backup.push(stack.pop());
}
while (!backup.isEmpty()) {
infix.append(backup.pop());
}
infix.append(')');
return infix.toString();
}
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')';
}
public static void main(String[] args) {
String infix1 = "(3-(7*2))";
String postfix1 = "372*-";
String infix2 = "((7+1)*((3-6)*(5-2)))";
String postfix2 = "71+36-52-**";
System.out.println(" postfix1: " + postfix1);
s = postfixToInfix(postfix1);
System.out.println("postfixToInfix(postfix1): " + s);
if (s.equals(infix1)) {
System.out.println(" Korrekt!");
} else {
System.out.println(" Nicht korrekt!");
}
System.out.println();
System.out.println(" postfix2: " + postfix2);
s = postfixToInfix(postfix2);
System.out.println("postfixToInfix(postfix2): " + s);
if (s.equals(infix2)) {
System.out.println(" Korrekt!");
} else {
System.out.println(" Nicht korrekt!");
}
System.out.println();
}
}
Output
postfix1: 372*-
postfixToInfix(postfix1): (3-(7*2))
Korrekt!
postfix2: 71+36-52-**
postfixToInfix(postfix2): ((5(-*2)()**)(3-6)(7+1))
Nicht korrekt!
Process finished with exit code 0
Instead of dealing with the parenthesis and everything as separate entries in the stack, you could use strings to simplify the process:
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
public static String postfixToInfix(String postfix) {
Stack<String> s = new Stack<String>();
for (char c : postfix.toCharArray()) {
if (isOperator(c)) {
String temp = s.pop();
s.push('(' + s.pop() + c + temp + ')');
} else {
s.push(String.valueOf(c));
}
}
return s.pop();
}

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

Categories

Resources