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?
Related
I'm having a bit of trouble trying to create a recursive method that counts the number of periods and spaces in a string. I can do this pretty easily using iteration, but I'm still fairly new to the concept of recursion. Here's my code so far,
could anyone tell me where I'm going wrong?
public static int periodsAndSpaces(String s){ //option 3
if(s.length()<0){ //base case
return 0;
}
else if(s.charAt(0) == ' ' || s.charAt(0) == '.'){ //general case
return periodsAndSpaces(s.substring(1)) + 1;
}
return 0;
}
package com.test.demo;
public class Counter {
public static void main(String[] args) {
System.out.println(new Counter().countPeriodsAndSpaces(" test. . .a"));
}
int countPeriodsAndSpaces(String rs) {
if (rs == null || rs.isEmpty())
return 0;
char c = rs.charAt(0);
if (c == ' ' || c == '.')
return 1 + countPeriodsAndSpaces(rs.substring(1));
else
return countPeriodsAndSpaces(rs.substring(1));
}
}
// Output 6
New method with everyone's suggestions:
public static int periodsAndSpaces(String s){ //option 3
if(s.length()==0){ //base case
return 0;
}
else if(s.charAt(0) == ' ' || s.charAt(0) == '.'){
return periodsAndSpaces(s.substring(1)) + 1;
}
else{
return periodsAndSpaces(s.substring(1));
}
}
Method stops running when there are no more characters left in the string, and I've added another case for adding onto the sum of periods and spaces when the current char doesn't have either of these.
I need to use a six letter word and if it has a sequence of letter number letter number letter number, then it will be a valid piece of data. Otherwise, it will be considered invalid. The problem with my code is, it always runs it as valid. Here is my code:
vstatus=false;
char a=pcode.charAt(0);
char b=pcode.charAt(1);
char c=pcode.charAt(2);
char d=pcode.charAt(3);
char e=pcode.charAt(4);
char f=pcode.charAt(5);
if(!Character.isLetter(a)) vstatus=true;
if(!Character.isDigit(b)) vstatus=true;
if(!Character.isLetter(c)) vstatus=true;
if(!Character.isDigit(d)) vstatus=true;
if(!Character.isLetter(e)) vstatus=true;
if(!Character.isDigit(f)) vstatus=true;
if (vstatus=true)
{
System.out.println(convertUpperCase(pcode)+" is a valid postal code");
}
if (vstatus=false)
{
System.out.println(convertUpperCase(pcode)+" is not a valid postal code");
}
I gues this would be shorter code for your problem:
String pcode = "aza2a3";
String regex = "[A-Za-z]{1}[\\d]{1}[A-Za-z]{1}[\\d]{1}[A-Za-z]{1}[\\d]{1}";
boolean matches = pcode.matches(regex);
System.out.println(matches);
matches is true if your string is in form that you need and false if i does not match your required string
In your code, even if one character is correct and all the others are wrong, you make it true. You need to confirm that all the characters are correct. Use &&.
String pcode = "i8i8i8";
char a=pcode.charAt(0);
char b=pcode.charAt(1);
char c=pcode.charAt(2);
char d=pcode.charAt(3);
char e=pcode.charAt(4);
char f=pcode.charAt(5);
if (Character.isLetter(a) && Character.isDigit(b) && Character.isLetter(c) && Character.isDigit(d) && Character.isLetter(e) && Character.isDigit(f)) {
System.out.println("valid");
} else {
System.out.println("not a valid postal code");
}
Or, in a loop:
String pcode = "i8i8i8";
boolean flag = true;
for (int i = 0; i < pcode.length(); i++) {
if (!(i % 2 == 0 && Character.isLetter(pcode.charAt(i)) || Character
.isDigit(pcode.charAt(i)))) {
flag = false;
}
}
if (flag) { System.out.println("valid"); }
else { System.out.println("not valid"); }
Ideally, extract the code into a method:
static boolean isPcodeValid(String s) {
for (int i = 0; i < s.length(); i++) {
if (!(i % 2 == 0 && Character.isLetter(s.charAt(i)) || Character
.isDigit(s.charAt(i)))) {
return false;
}
}
return true;
}
Or, use some Java8+ features:
static boolean isPcodeValid(String s) {
return IntStream.range(0, s.length())
.allMatch(i -> i % 2 == 0 && Character.isLetter(s.charAt(i)) || Character
.isDigit(s.charAt(i)));
}
Finally,
You may use this regex:
String r = [A-Za-z][\d][A-Za-z][\d][A-Za-z][\d]
if (pcode.matches(r)) {
// valid
} else {
// invalid
}
5 different ways, choose the one that suits you the best.
See if you guys can solve this. I wrote a title caps program in Java, that is a program which can take a string of ASCII characters and make all words (substrings made up of only letters A-Z or a-z) into title case. So the string "##hello!_world$" becomes "##Hello!_World$". But this program refuses to correctly translate non letters at the first indice of the string despite my best efforts to correct it.
public static String LetterCapitalize(String str) {
String newStr = "";
System.out.println(newStr);
for (int i = 0; i < str.length(); i++) {
// if first character is a letter and not uppercase
if (i == 0 && (!isUpperCase(str.charAt(i)))) {
Character m = (char) ((int) str.charAt(i) - 32);
newStr = newStr + m;
} // if first character is a letter and uppercase
else if (i == 0 && (isUpperCase(str.charAt(i)))) {
Character m = str.charAt(i);
newStr = newStr + m;
} // if first character is not a letter
else if (i == 0 && (!isLetter(str.charAt(i)))) {
Character m = str.charAt(i);
newStr = newStr + m + m;
} // if character is first letter in a word
else if (!isLetter(str.charAt(i - 1)) && isLetter(str.charAt(i)) && !isUpperCase(str.charAt(i))) {
Character m = (char) ((int) str.charAt(i) - 32);
newStr = newStr + m;
} // all other
else {
Character m = str.charAt(i);
newStr = newStr + m;
}
}
return newStr;
}
public static boolean isUpperCase(char c) {
boolean isCap;
if (c >= 'A' && c <= 'Z') {
isCap = true;
} else {
isCap = false;
}
return isCap;
}
public static boolean isLetter(char c) {
boolean isLetter;
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
isLetter = true;
} else {
isLetter = false;
}
return isLetter;
}
this line is wrong: if (i == 0 && (!isUpperCase(str.charAt(i)))) { - it assumes it's a lowercase letter. You need to see if it's a lowercase letter. Not all characters that aren't uppercase are letters. So you should have some thing like
if (i==0 && isLetter() && !isUpperCase())
The other way to do it is have the check for it being a letter come first.
I am writing a pig latin code and I am tripped up by how to get my program to identify where the next vowel in the word is if the first letter in the word is a consonant. Then it moves the first part of the word, up to the first vowel, to the end of the word and prints ay along with it. (ex. trees = eestray)
This is the code I have now
// word is bringing in the string entered from the user
public static void translate(String word) {
String wordCap, pigLatin = "";
char vowels;
int lowest = 0, tempOne, tempTwo, tempThree, tempFour, tempFive;
wordCap = word.toUpperCase();
vowels = wordCap.charAt(0);
if (vowels == 'A' || vowels == 'E' || vowels == 'I' || vowels == 'O' || vowels == 'U') {
word = word + "way";
System.out.println(word);
}
else {
tempOne = wordCap.indexOf('A', 1);
if (lowest > tempOne && tempOne != -1) {
lowest = tempOne;
}
tempTwo = wordCap.indexOf('E', 1);
if (lowest > tempTwo && tempTwo != -1) {
lowest = tempTwo;
}
tempThree = wordCap.indexOf('I', 1);
if (lowest > tempThree && tempThree != -1) {
lowest = tempThree;
}
tempFour = wordCap.indexOf('O', 1);
if (lowest > tempFour && tempFour != -1) {
lowest = tempFour;
}
tempFive = wordCap.indexOf('U', 1);
if (lowest > tempFive && tempFive != -1) {
lowest = tempFive;
}
public static char vowel(String word) {
int start= 0, end= 0;
char vowels;
for (int i = 0; i < word.length(); i++) {
vowels = word.charAt(i);
if (vowels == 'A' || vowels == 'E' || vowels == 'I' || vowels == 'O' || vowels == 'U') {
end = i;
break;
}
}
return (char) end;
}
(in translate method)
for (int i = 0; i<wordCap.length(); i++) {
if (vowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
}
}
The problem now is that the vowel method is not an applicable method type. It says it must be a char?
Let me try to shorten that method for you ;)
Try something like this:
private static final char[] vowels = {'a', 'e', 'i', 'o', 'u'};
public static String translate(String word) {
int start = 0; // start index of word
int firstVowel = 0;
int end = word.length(); // end index of word
for(int i = 0; i < end; i++) { // loop over length of word
char c = Character.toLowerCase(word.charAt(i)); // char of word at i, lower cased
if(Arrays.asList(vowels).contains(c)) { // convert vowels to a list so we can use List.contains() convenience method.
firstVowel = i;
break; // stop looping
}
}
if(start != firstVowel) { // if start is not equal to firstVowel, we caught a vowel.
String startString = word.substring(firstVowel, end);
String endString = word.substring(start, firstVowel) + "ay";
return startString+endString;
}
return word; //couldn't find a vowel, return original
}
What this snippet does, is iterate over every character in the word, storing the index of the first vowel in the firstVowel variable. Then, we get every character from firstVowel to end; and store it in startString. Then, we get every character from start to firstVowel; add "ay", and store it in endString. Finally, we concatenate these strings together and return them, resulting in the desired output.
We can test this with System.out.println(translate("trees"));
EDIT: Without array, as requested:
public static String translate(String word) {
char a = 'a';
char e = 'e';
char i = 'i';
char o = 'o';
char u = 'u';
int start = 0;
int firstVowel = 0;
int end = word.length();
for(int i = 0; i < end; i++) {
char c = Character.toLowerCase(word.charAt(i));
if(c == a || c == e || c == i || c == o || c == u) {
firstVowel = i;
break;
}
}
if(start != firstVowel) {
String startString = word.subString(firstVowel, end);
String endString = word.subString(start, firstVowel) + "ay";
return startString+endString;
}
return word;
}
As you can see, arrays shorten things up quite a bit!
If you're feeling pedantic about the Arrays.asList().contains() call, we could define our own:
public static boolean containsChar(char[] lookIn, char lookFor) {
boolean doesContainChar = false;
for(char c : lookIn) {
if(doesContainChar = c == lookFor)
break;
}
return doesContainChar;
}
You might want to use a for loop to iterate through the letters of each word until it finds a vowel. Example:
String wordCap = word.toUpperCase();
char vowels;
for (int i=0; i<wordCap.length(); i++) {
if (isVowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
break;
}
}
Of course, I only used isVowel() for the sake of keeping the example concise. You'll have to identify it as a vowel the same way you did in your first if statement (or write an isVowel() method yourself).
For modifying the word, you'll also want to declare a variable to hold the index of the vowel. The previous section of code could be added to for this, like so:
String wordCap = word.toUpperCase();
char vowels;
int vowelIndex;
String newWord;
for (int i=0; i<wordCap.length(); i++) {
if (isVowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
vowelIndex = i;
break;
}
}
Then you could reference vowelIndex when modifying the word.
if (vowelIndex == 0) {
newWord = word + "way";
} else {
newWord = word.substring(vowelIndex) + word.substring(0, vowelIndex) + "ay";
}
return word;
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;
}
}