I'm trying to write a program that checks a user supploed sentence and converts it to Pig Latin. I'm trying to have the program check to see if the first letter is a vowel or not and return that using a boolean expression. Next I'm trying to get the program to cut off the first letter from the word and add it to the end of the word. Finally its supposed to add way if it is a vowel and ay if it not a vowel. Any help or advice will be greatly appreciated.
public class PigLatin {
public static void main(String[] argv) {
if (argv.length > 0) {
for (int i = 0; i < argv.length; i++) {
char firstLetter = aStringVariable.charAt(0);
}
}
public static boolean isVowel(char c) {
char[] vowels = new char[] {'a', 'e', 'i', 'o', 'u', 'y'};
for(int i = 0; i < vowels.length; i++) {
if(Character.toString(vowels[i]).equalsIgnoreCase(Character.toString(c))) {
return true;
}
}
return false;
}
public static String makePigLatin(boolean vowel, String word)
{
String everythingButTheFirstLetter = word.substring(1);
String n = everythingButTheFirstLetter + firstLetter;
if (true)
{
System.out.println(n + "way");
}
if (false)
{
System.out.println(n + "ay");
}
}
}
Try something like this -
public static class PigLatin {
public static boolean isVowel(char c) {
switch (Character.toLowerCase(c)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return true;
}
return false;
}
public static String makePigLatin(String word) {
char firstLetter = word.charAt(0);
String everythingElse = word.substring(1);
String n = everythingElse + firstLetter;
if (isVowel(firstLetter)) {
return n + "way";
}
return n + "ay";
}
}
public static void main(String args[]) {
String[] words = { "fair", "away", "test" };
for (String word : words) {
String s = PigLatin.makePigLatin(word);
System.out.println(word + " is " + s);
}
}
Output is
fair is airfay
away is wayaway
test is esttay
You can also try something like:
public static string PigLatin(string sentence)
{
const string vowels = "AEIOUaeiou";
sentence = sentence.ToLower();
var returnSentence = "";
foreach (var word in sentence.Split())
{
var firstLetter = word.Substring(0, 1);
var restOfWord = word.Substring(1, word.Length - 1);
var currentLetter = vowels.IndexOf(firstLetter, StringComparison.Ordinal);
if (currentLetter == -1)
{
returnSentence += restOfWord + firstLetter + "ay ";
}
else
{
returnSentence += word + "way ";
}
}
returnSentence = returnSentence.TrimEnd();
return returnSentence;
}
The output for the sentence "The Quick Brown Fox Jumped Over The Lazy Dog" will be :
hetay uickqay rownbay oxfay umpedjay veroay hetay azylay ogday
Related
I'm writing a program that has two rules:
1. If the first character of the word is a vowel, then move it to the end of the word.
2. If the first character of the word is a consonant, then move it to the end of the word and append 'ae'.
import java.util.Scanner;
public class Program5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String english = scanner.nextLine();
String piggy = piggyEnglish(english);
System.out.print("Translated: " + piggy);
}
private static String piggyEnglish(String s) {
String piggy = "";
int i = 0;
while (i<s.length()) {
while (i<s.length() && !isLetter(s.charAt(i))) {
piggy = piggy + s.charAt(i);
i++;
}
if (i>=s.length()) break;
int begin = i;
while (i<s.length() && isLetter(s.charAt(i))) {
i++;
}
int end = i;
piggy = piggy + piggyWord(s.substring(begin, end));
}
return piggy;
}
private static boolean beginsWithVowel(String word){
String vowels = "aeiou";
char letter = word.charAt(0);
return (vowels.indexOf(letter) != -1);
}
private static boolean isLetter(char c) {
return ( (c >='A' && c <='Z') || (c >='a' && c <='z') );
}
private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split) + word.substring(0, split);
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}
private static int firstVowel(String word) {
word = word.toLowerCase();
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')
return i;
return 0;
}
}
The following is the expected output:
Please enter a sentence: today is a beautiful day
Translated: odaytae si a eautifulbae aydae
However, this is what I'm getting:
Please enter a sentence: today is a beautiful day
Translated: odaytae is a eautifulbae aydae
Basically, it doesn't translate any words that start with a vowel. I think the problem stems from the piggyWord method, but I'm not certain. Can I get any pointers on how to fix this?
The error lies in the piggyWord function:
private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split + 1) + word.substring(0, split + 1); //Since vowel is in 1st place, substring(0,0) returns empty string.
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}
Based on your rules, you don't need the method firstVowel() to get the index of the first vow in a word because you only need to know whether the first character in the word is a vow or not.
So simply change you piggyWord method to the following will solve your problem:
private static String piggyWord(String word) {
if(beginsWithVowel(word)) {
return word.substring(1) + word.substring(0, 1);
} else {
return word.substring(1) + word.substring(0, 1)+"ae";
}
}
Or more simply:
private static String piggyWord(String word) {
String result = word.substring(1) + word.substring(0, 1);
return beginsWithVowel(word) ? result : result + "ae";
}
Because you always have to move the first character of a word to the end, the only thing is that whether you need to append an extra "ae" in the end or not.
If only the first letter is concerned than in "firstVowel" you can return 1 if vowel is at first position.
private static int firstVowel(String word) {
word = word.toLowerCase();
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')
return 1;
return 0;
}
This is a recursion program to test whether or not a sentence is a palindrome. It will run correctly if I write "bob" but not for "Madam I'm Adam" because of the caps and symbols. We are required to use a clean string method(?) to eliminate the spaces, symbols, and caps. This is what I have but I don't believe I've implemented it correctly. Could someone tell me how to improve/fix this? (Yes, I've looked all over the internet)
import java.util.Scanner;
public class Palindromes {
public static boolean isaPalindrome(String s) {
String cleanedString = clean(s);
if (s.length() == 0 || s.length() == 1)
return true;
if (s.charAt(0) == s.charAt(s.length() - 1))
return isaPalindrome(s.substring(1, s.length() - 1));
return false;
}
public static void main(String[] args) {
System.out.print("Enter a palindrome to test: ");
Scanner console = new Scanner(System.in);
String inStr = console.nextLine();
if (isaPalindrome(inStr)) {
System.out.printf("The input string, %s, is a palindrome.\n",
inStr);
reverseStr(inStr); // must be recursive!
System.out.println();
} else {
System.out.printf("The input string, %s, is not a palindrome.\n",
inStr);
}
}
private static String clean(String s) {
String cleaned = "";
return cleaned;
}
private static String reverseStr(String inStr) {
if ((null == inStr) || (inStr.length() <= 1)) {
return inStr;
}
return reverseStr(inStr.substring(1)) + inStr.charAt(0);
}
}
Your recursive method isaPalindrome is correct. If you want to further improve it, I would suggest you to avoid using subString to create parameters for your recursive call, this will create too many strings.
Instead, keep track of the positions of the characters in the original string that you are comparing:
public static boolean isaPalindrome(String s, int leftIndex, int rightIndex) {
if (leftIndex == rightIndex) return true;
if (s.charAt(leftIndex) == s.charAt(rightIndex))
return isaPalindrome(s, leftIndex + 1, rightIndex - 1);
return false;
}
You would invoke the method as: isaPalindrome(inStr, 0, inStr.length() - 1)
As for your clean method, you can use toLowerCase and Character.isLetter method to process the original string.
private static String clean(String s) {
String lowerCaseString = s.toLowerCase();
StringBuffer result = new StringBuffer();
for (int i = 0; i < lowerCaseString.length(); ++i) {
if (Character.isLetter(lowerCaseString.charAt(i))) {
result.append(lowerCaseString.charAt(i));
}
}
return result.toString();
}
Try this:
public static void main(final String[] args) {
final String unclean = "Madam I'm Adam";
final String clean = cleanString(unclean);
System.out.println("Clean string is: " + clean);
}
static private String cleanString(final String pTheString) {
final StringBuilder sb = new StringBuilder(pTheString.length());
for (final char c : pTheString.toCharArray()) {
switch (c) {
// ignore all those
case ' ':
case '\'':
case '.':
break;
// write the rest
default:
sb.append(c);
}
}
return sb.toString().toLowerCase();
}
public static void main(String[] args)
{
Scanner sentence = new Scanner(System.in);
System.out.println("This program will determine if an inputted phrase is a palindrome.");
System.out.println(" ");
System.out.println("Enter a phrase, word, or sentence:");
String a = sentence.nextLine();
String b = a.toLowerCase().replaceAll("[^a-z]"," "); //as long as the words are spelt the same way, the caps don't matter and it ignores spaces and punctuation
System.out.println();
System.out.println(palindromeChecker(b)); //calls method
}
public static String palindromeChecker(String b)
{
String reverse = new StringBuilder(b).reverse().toString();
String c;
if(b.equals(reverse)) {
c = "The word " +b+ " is a palindrome"; }
else {
c = "The word " +b+ " is not a palindrome"; }
return c;
}
}
My, problem is that for example, if i do Eva, can I see bees in a cave? It should be a palindrome, however it's not can u please help me with this and please try not to make it complicated.
Replace:
String b = a.toLowerCase().replaceAll("[^a-z]"," ");
With
String b = a.toLowerCase().replaceAll("[^a-z]","");
Otherwise, you're replacing non-alphabetical characters with spaces, which can influence the checking of the reverse String.
You need to remove all non-letters from your string:
public class Palindrome {
public static String strip(String s) {
return s.toLowerCase().replaceAll("[^a-z]", "");
}
public static boolean isPalindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(strip("Eva, can I see bees in a cave?"));
System.out.println(isPalindrome(strip("Eva, can I see bees in a cave?")));
}
}
Output:
evacaniseebeesinacave
true
public class PalindromeStringWithReverse {
public static void main(String[] args) {
String str = "21raceca r12";
str = str.replaceAll(" ", "");
boolean isPalindrome = false;
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) == str.charAt((str.length() - 1) - i)) {
isPalindrome = true;
continue;
}
isPalindrome = false;
}
if (isPalindrome) {
System.out.println("Palindrome");
} else {
System.out.println("not palindrome");
}
}
}
I am trying to build something like a hangman (for beginners)
I try this:
int i = 0;
int fails = 0;
boolean success = false;
boolean retval;
char[] defineword = new char[] { 'h', 'u', 'n', 'g' };
char[] givenchar = new char[0];
char[] testchar = new char[] { 'h' };
while (success == false && fails < 5) {
System.out.println("Give a char: ");
String word = input.next(); // INPUT STRING
givenchar = word.toCharArray(); // CONVERT
retval = Arrays.equals(givenchar, testchar);
System.out.println("THE LETTER IS " + retval);
if (retval == true) {
testchar[0] = defineword[i + 1];
} else {
fails++;
}
}
The problem is that it can't continue after the letter ('u'), it is stuck in 'u'.
One observation I will make is that you only real comparison is between givenchar, and testchar.
retval = Arrays.equals(givenchar, testchar);
It would make sense that this wouldn't work once you got past u because testchar never gets past u either. I think you might have intended to add an i++ somewhere.
testchar[0] = defineword[i + 1];
package mer;
import java.util.Scanner;
public class Aswe
{
int i=0;
int f=0;
boolean suc=false;
boolean ret;
char[] dw=new char[]{'h','u','n','g'};
char[] gc=new char[0];
char[] tc=new char[]{'h'};
Scanner i1;
public void me()
{
i1=new Scanner(System.in);
while(suc==false&&f<5)
{
System.out.println("give a char");
String ch=i1.nextLine();
gc=ch.toCharArray();
ret=eual(gc,tc);
System.out.println("the letter is"+ret);
if(ret)
{
tc[0]=dw[i+1];
}
else
f++;
}
}
public boolean eual(char[] a,char[] b)
{
if(a[0]==b[0])
return true;
else
return false;
}
public static void main(String ... args)
{
new Aswe().me();
}
}
private int fails = 0;
private final int maxFails = 5;
private char[] answer = new char[] {'j','a','v','a'};
public Hangman() {
Scanner scan = new Scanner(System.in);
/*
* Game Loop
*/
while(fails < maxFails){
System.out.print("Enter a char: ");
char givenChar = scan.next().charAt(0);
System.out.println("Given char is: " + Check(answer,givenChar));
}
}
/*
* Check if the char exists in the array.
*/
private boolean Check(char[] array,char value){
for(int i = 0; i < array.length; i++){
if(array[i] == value){
return true;
}
}
/*
* Okay did not find any char that match return false.
*/
return false;
}
I am working on some code for homework and for the life of me can't figure out why this won't run. It ran until I added in the methods for file reading, which I know worked in another program. I took the code directly from some of my other work. So, can someone much better at Java than I tell me what I am doing wrong to have this problem? As this is homework please don't tell me how to fix any other problems, but I wouldn't discourage hints about them.
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class vowels_r_us {
//for file reading
private static FileInputStream inFile;
private static InputStreamReader inReader;
private static BufferedReader reader;
//pasrsing input from file
private static StringTokenizer strTkn;
public static void main(String[] args)
{
initFile(); //prepare file for reading
while (reader.ready())//iterate as long as there is more avaliable data
{
String word, suffix, line;
line = getWordSuffix();
word = line.substring(0, line.indexOf(' '));
suffix = line.substring(line.indexOf(' '));
}
}
/*CONJUGATION METHODS*/
static String pluralize(String s)
{
String pluralForm;
switch (classifyEnding(s))
{
case 'c':
pluralForm = s.concat("GH");
break;
case 'v':
pluralForm = s.substring(0, s.length() - 1).concat("G");//drop last letter add G
break;
case 'd':
pluralForm = s + s.charAt(s.length() - 1) +"H";//double last letter, then add H
break;
default:
pluralForm = "If you are getting this something is broken, have fun debugging.";
break;
}
return pluralForm;
}
static String addSuffix(String word, String suffix)
{
String suffixAdded;
switch (classifyEnding(word))
{
case 'c':
suffixAdded = word + suffix;
break;
case 'v':
if(isVowel(suffix.charAt(0)))
{
suffixAdded = word + suffix.substring(1);//word + drop first letter of suffix then add suffix
}
else
{
suffixAdded = word + suffix.charAt(0) + suffix;//word + first letter of suffix + suffix
}
break;
case 'd':
if(isVowel(suffix.charAt(0)))
{
suffixAdded = word + suffix.charAt(0) + suffix;//word + first letter of suffix + suffix
}
else
{
suffixAdded = trimRepeatSequence(word) + suffix;
}
break;
default:
suffixAdded = "If you are getting this something is broken, have fun debugging.";
break;
}
return suffixAdded;
}
/*END CONJUGATION METHODS*/
/*STRING MODIFICATION AND TESTING METHODS*/
//removes lefmost vowel or consonant from sequence
static String trimRepeatSequence(String s)
{
String editedString = "";
boolean vBasedEnding = isVowel(s.charAt(s.length() - 1));
for (int i = s.length() - 1; i >= 0; i--)
{
if (isVowel(s.charAt(i)) != vBasedEnding)
{
editedString = s.substring(0, i+1) + s.substring(i+2, s.length());
break;
}
}
return editedString;
}
/* classify endings in to three grammatical categories, single vowel ending 'v', single consonant ending 'c', double type ending 'd'
*/
static char classifyEnding(String s)
{
char grammaticalClass;
if (isVowel(s.charAt(s.length()- 1)) == isVowel(s.charAt(s.length()- 2)))
{
grammaticalClass = 'd';
}
else
{
grammaticalClass = isVowel(s.charAt(s.length()- 1)) == true? 'v' : 'c';
}
return grammaticalClass;
}
static boolean isVowel(char c)
{
boolean b;//rename
switch (Character.toLowerCase(c))
{
case 'a': case 'c':
case 's': case 'l':
b = true;
break;
default:
b = false;
break;
}
return b;
}
/*END STRING MODIFICATION AND TESTING METHODS*/
/*FILE READER METHODS*/
//read file for input
public static void initFile() throws IOException
{
inFile = new FileInputStream ("C:\\Users\\Tom\\Dropbox\\!!VHSAPCSData\\VHSP35data.txt");
inReader = new InputStreamReader(inFile);
reader = new BufferedReader(inReader);
}
public static String getWordSuffix() throws IOException
{
String line;
line = reader.readLine();
return line;
}
}
You need to wrap your IO code in a try / catch:
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
taken from: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html