How to convert user input string to pig latin? - java

Im trying to convert a user entered string that starts with a consonant to pig latin buy moving all the consonants to the end of the word till the word starts with a vowel, and then adding "ay" to the end of the word. I have a for loop that's supposed to do this, but for some reason, it outputs nothing. What am i doing wrong here? Im stumped.
Here's the code:
import java.util.Scanner;
public class two {
public static void main(String[] args) {
System.out.println("Please enter a word");
Scanner word = new Scanner(System.in);
String pigLatin = word.nextLine();
while (!pigLatin.equalsIgnoreCase("quit")) {
if (isVowel(pigLatin.charAt(0))) {
pigLatin = (pigLatin + "way");
System.out.println(pigLatin);
}
else {
for (int i = 0; i < pigLatin.length(); i++) {
char firstChar = pigLatin.charAt(0);
pigLatin = pigLatin.substring(1);
pigLatin = pigLatin + firstChar;
if (i >= pigLatin.length())
{
pigLatin = pigLatin + "ay";
System.out.println(pigLatin);
}
}
}
System.out.println("Please enter a word");
pigLatin = word.nextLine();
}
word.close();
}
private static boolean isVowel(char ch) {
char v = Character.toLowerCase(ch);
if (v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u') {
return true;
}
else {
return false;
}
}
}

You need a less than or equal <= on the i otherwise i is never greater than or equal to pigLatin.length().
for (int i = 0; i <= pigLatin.length(); i++) {
char firstChar = pigLatin.charAt(0);
pigLatin = pigLatin.substring(1);
pigLatin = pigLatin + firstChar;
if (i >= pigLatin.length())
{
System.out.println(pigLatin);
}
}

your for loop condition is
i < pigLatin.length()
and you said in if
if(i >= pigLatin.length()){....}
so this condition will never be true , for that reason there is no output,
see below code ,
import java.util.Scanner;
/**
*
* #author rahmat waisi
*/
public class PigLatin {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
// System.out.print("Please enter a word: , Enter [ quit ] for exit : ");
String pigLatin = scanner.nextLine();
if (pigLatin.equals("quit")) {
break;
}
if (isVowel(pigLatin.charAt(0))) {
pigLatin += "ay";
System.out.println(pigLatin);
} else {
String output = "";
int separation_index = findFirstVowel(pigLatin);
if (separation_index ==-1) {
System.out.println(pigLatin+"ay");
continue;
}
output+= pigLatin.substring(separation_index);
output+= pigLatin.substring(0, separation_index) + "ay";
System.out.println(output);
}
}
}
}
private static boolean isVowel(char ch) {
char v = Character.toLowerCase(ch);
return v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u';
}
private static int findFirstVowel(String str) {
for (int i = 0; i < str.length(); i++) {
if (isVowel(str.charAt(i))) {
return i;
}
}
return -1;
}
}
here is some input:
pig
banana
trash
happy
duck
glove
eat
omelet
are
ffff
quit
and their output is:
igpay
ananabay
ashtray
appyhay
uckday
oveglay
eatay
omeletay
areay
ffffay

Related

java not getting output piglatin

The following is my code for converting all the words of the sentence into PigLatin, ie "Her food is stolen" to "ERHAY OODFAY ISAY OLENSTAY", but the output which I am getting is ERHAY. Any corrections would be appreciated. Thanks.
public class piglatin
{
public void main(String s)
{
s=s.toUpperCase();
s=s+" ";
int l=s.length();
String word="";
int n=0;
int w=0;//no of words in s(loop1)
int wor=0;//no of words loop2
for(int i=0;i<l;i++)
{char c=s.charAt(i);
if(c==' ')
w++;
}
for(int i=0;i<l;i++)
{ char c=s.charAt(i);
int m=s.indexOf(' '); //length of first word
if(i==0)
{ for(int j=0;j<m;j++)
{char c1=s.charAt(j);
if(c1=='A'||c1=='E'||c1=='I'||c1=='O'||c1=='U')
{n=j;//index of first vowel
j=m;}
}
word=s.substring(n,m)+s.substring(0,n);
System.out.print(word+"AY"+" ");
}
if(c==' '&&wor!=w-1)
{ s=s.substring(m+1,l);
l=s.length();
i=0;
wor++;
}
if(wor==w-1)
i=l+1;
}
}
}
You can simplify it greatly by splitting the sentence on whitespace and processing each word of the resulting array.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = scanner.nextLine();
s = s.toUpperCase();
String[] words = s.split("\\s+");// Split s on whitespace
// Process each word from words[]
for (String word : words) {
int m = word.length(), j;
for (j = 0; j < word.length(); j++) {
char c1 = word.charAt(j);
if (c1 == 'A' || c1 == 'E' || c1 == 'I' || c1 == 'O' || c1 == 'U') {
break;
}
}
String translated = word.substring(j, m) + word.substring(0, j);
System.out.print(translated + "AY" + " ");
}
}
}
A sample run:
Enter a sentence: Her food is stolen
ERHAY OODFAY ISAY OLENSTAY
Alternatively, in addition to using String#indexOf​(int ch), you can use String#indexOf​(String str, int fromIndex) to get all the words of the sentence.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = scanner.nextLine();
s = s.toUpperCase();
// Start from index, 0
int fromIndex = 0, lastPositionOfWhitespace = -1;
for (int i = 0; i < s.length(); i++) {
int indexOfWhitespace = s.indexOf(' ', fromIndex);
String word = "";
if (indexOfWhitespace != -1) {
lastPositionOfWhitespace = indexOfWhitespace;
word = s.substring(fromIndex, indexOfWhitespace);
fromIndex = indexOfWhitespace + 1;
} else {
word = s.substring(lastPositionOfWhitespace + 1);// Last word of the sentence
i = s.length();// To stop further processing of the loop with counter, i
}
int m = word.length(), j;
for (j = 0; j < word.length(); j++) {
char c1 = word.charAt(j);
if (c1 == 'A' || c1 == 'E' || c1 == 'I' || c1 == 'O' || c1 == 'U') {
break;
}
}
String translated = word.substring(j, m) + word.substring(0, j);
System.out.print(translated + "AY" + " ");
}
}
}
A sample run:
Enter a sentence: Her food is stolen
ERHAY OODFAY ISAY OLENSTAY

For loop is printing out multiple print statements

I'm making a program for class which prints out the number of vowels in a word and any help would be appreciated. Currently, the program prints out the correct number of vowels but also prints out the print statement, "vowels:" multiple times before. I've tried moving the print statement and the braces around but it says "error: 'else if' without 'if'". I'm completely new to Java so sorry if the solution is in plain sight. Thank you in advance :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels= 0;
int l;
l= text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i,i+1);
if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0||
wordPRT.compareToIgnoreCase("i")==0
|| wordPRT.compareToIgnoreCase("o")==0
|| wordPRT.compareToIgnoreCase("u")==0){
vowels++;
System.out.println("vowels: " + vowels);
}
else if(vowels<1){
System.out.print("no vowels");
}
}
}
}
You are printing everything in a for loop instead of count vowels and print at the end.
try something like:
int vowelsCounter = 0;
for(...) {
... logic to count the vowels
if(isvowel(string.charAt(i)){
vowelsCountr++;
}
}
if(vowelsCounter > 0 ) {
printSomething
}
else {
print something else
}
Also You should not use subString for this kind of a loop but string.charAt(i)
Move the print statements out of the for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels = 0;
int l;
l = text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i, i + 1);
if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
|| wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
|| wordPRT.compareToIgnoreCase("u") == 0) {
vowels++;
}
}
if (vowels >= 1) {
System.out.println("vowels: " + vowels);
} else {
System.out.print("no vowels");
}
}
}
A sample run:
Enter text: Hello
vowels: 2

print the word which has maximum number of vowel in java

I want to print the word which is containing maximum number of vowel. But Problem is that last word of sentence which is containing maximum number is not print. please help me solve that problem. My code is below.
When i enter input 'Happy New Year', Output is 'Yea' .But i want i output is 'Year'
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Word : ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for (int i = 0; i < sentence.length(); i++) {
ch = sentence.charAt(i);
if (ch != ' ' && i != (sentence.length() - 1)) {
word += ch;
ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
} else {
if (vowelCount > temp) {
temp = vowelCount;
wordMostVowel = word;
}
word = "";
vowelCount = 0;
}
}
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
}
}
You cut words at spaces (correct), but you also cut at the last character, even if it's not a space (so this character is never dealt with). And that's not correct.
Here is a possibility:
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String sentence = sc.nextLine();
String wordMostVowels = "";
int maxVowelCount = 0;
for (String word : sentence.split(" ")) {
int vowelCount = 0;
for (char c : word.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
wordMostVowels = word;
}
}
System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
}
}

Removing vowels from an input string using a loop

I need my output to only be 5 characters long NOT counting the removed vowels. Currently my code is counting the input length and returning that number minus the vowels. This might be confusing. If I input "idontthinkso" it only returns "dnt" instead of what I want it to print out which is "dntth". Btw, I'm not allowed to use Stringbuilder or anything like that, only a loop, so forgive the code. How can I fix this? Here is my code:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for (int i = 0; i < tweetLengthAllowed; i++) {
char c = input.charAt(i);
if (c == 'a' ||
c == 'e' ||
c == 'i' ||
c == 'o' ||
c == 'u' ||
c == 'A' ||
c == 'E' ||
c == 'I' ||
c == 'O' ||
c == 'U') {
f = 1;
} else {
s = s += c;
f = 0;
}
}
System.out.println(s);
}
}
I'm very much in favor of using a while loop for this, but since you stated you can only use a for loop...
The problem is that your loop will iterate until i = 5, even if a vowel is detected. We need a way to tell the loop to pretend that never happened. You can't decrement i, or you'll be stuck at the same character forever.
Here's what I came up with, I decided to simply increment the tweetLengthAllowed to negate the i increment.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for(int i = 0; i < tweetLengthAllowed; ++i) { //Must be a for loop
char c = input.charAt(i);
if(c == 'a'|| c == 'e'|| c == 'i'|| c == 'o'|| c =='u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
f = 1;
tweetLengthAllowed++; //Allows the loop to continue for one more interation
} //end if
else{
s = s += c;
f = 0;
}//end else
} //end for
System.out.println(s);
} //end main
} //end class
Also, if you're going to use a big chain of ORs, please do yourself a favor and make it more readable as I did above.
You can do this simpler. Here I iterate every char in the input and break if it reaches the limit:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int tweetLengthAllowed = 5;
int i = 0;
boolean isNotVowel;
boolean limitReached;
for (char c : input.toCharArray()) {
isNotVowel = "AEIOUaeiou".indexOf(c) == -1;
limitReached = tweetLengthAllowed <= i;
if (limitReached) { // exit the loop
break;
} else if (isNotVowel) { // append the char
s += c;
i++;
}
}
System.out.println(s);
}
}
Run output:
Type a tweet:
idontthinkso
dntth
Here is my way of doing it:-
import java.util.Scanner;
import java.lang.StringBuffer;
public class Program {
private static String RemoveVowel(String text)
{
int len = text.length();
char[]vowels = {'a','e','i','o','u','A','E','I','O','U'};
StringBuffer sb = new StringBuffer(text);
for(int i = 0;i<len;i++)
{
for(char v : vowels)
{
if(v == text.charAt(i))
{
sb.setCharAt(i,'\0');
}
}
}
return sb.toString();
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter some text to remove vowels from it: ");
String val = scan.nextLine();
System.out.println(RemoveVowel(val));
}
}
I have used string buffer to make the string modifiable and a "for" loop iterates through the length of the string, and one iterates through the "vowels" array; an "if" statement checks if the current character is equal to one of the vowels and if true, it sets the current character to null, which removes the vowel.
public class RemoveVowels {
public static void main(String[] args) {
String inputString = "Java - Object Oriented Programming Language";
System.out.println(inputString.replaceAll("[aeiouAEIOU]", " "));
}
}
Output:
J v - bj ct r nt d Pr gr mm ng L ng g

Palindrome coding

I am trying to create a Palindrome tester in java using a method.. This is what I have so far. It is so close I just can't figure out why it won't say that it IS a palindrome and reverse it.
System.out.println("Fun with Palindromes!!");
Scanner in = new Scanner(System.in);
System.out.println("Enter the potential palindrome (or enter exit to quit): ");
String x = in.nextLine();
while(!x.equals("exit"))
{
String t = x.toLowerCase();
String u = CleanUpString(t);
Boolean wordCheck = checkPalindrome(u);
int wordCount = x.length();
String rev = "";
for(int i = 0; i <x.length(); i++)
{
rev = x.charAt(i)+rev;
}
if(wordCheck == true)
{
System.out.println("The orginal string\"" + u + "\" contains" + wordCount + "characters." );
System.out.println("The converted string\"" + rev + "\"is a palindrome");
}
else if(wordCheck == false)
{
System.out.println("The string \"" + u + "\" contains " + wordCount + " characters");
System.out.println("\"" + rev + "\" is not a palindrome");
}
System.out.println("\nEnter the potential palindrome, or enter exit to quit: ");
x = in.nextLine();
}
}
public static String CleanUpString(String words)
{
words = words.replace(".","");
words = words.replace("," ,"");
words = words.replace(":","");
words = words.replace("!","");
return words;
}
public static boolean checkPalindrome(String baseball)
{
String rev = "";
for(int i = 0; i<baseball.length()-1; i++)
{
rev = baseball.charAt(i) + rev;
}
if(rev.equals(baseball))
return true;
else
return false;
}
}
Here is the code I used to determine whether a string is Palindrome String or not:
private static boolean checkPalindrome(String str){
if (str == null)
return false;
int len = str.length();
for (int i=0;i<len/2 ; i++){
if (str.charAt(i) != str.charAt(len - i - 1)){
return false;
}
}
return true;
}
For reversing strings, you can simply use:
String reverse = new StringBuffer(string).reverse().toString();
Hope these can help you.
Use StringUtils for this
import org.apache.commons.lang.StringUtils;
boolean isPalindrome(String word) {
return StringUtils.reverse(word).equals(word);
}
Here is another option
public class PalindromeTester {
public static void main(String[] args) {
try {
String s = args[0];
int i = args[0].length()-1;
int i2 = args[0].length();
char [] chrs = new char[i2];
for ( int i3 = i; i3 > -1; i3-- ) {
chrs[i2-i3-1] = (s.charAt(i3) );
}
String s2 = String.valueOf(chrs);
if ( s2.equals(s) ) {
System.out.println( s + " is a palindrome!");
} else {
System.out.println( s + " is not a palindrome");
}
} catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("Please enter at least one letter or digit!");
}
}
}
Here's how I did it:
public class palindromeTWO
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int right = 0;
int left = 1;
System.out.println("Please enter a word: ");
String word = scan.next();
int word_length = word.length();
while(word.charAt(right) == word.charAt(word_length - left) && left < (word_length / 2))
{
left++;
right++;
}
if(word.charAt(right) == word.charAt(word_length - left))
{
System.out.println("'" + word + "'" + " is a palindrome!");
}
else
{
System.out.println("'" + word + "'" + " is NOT a palindrome.");
}
}
}
1st implementation using recursion -
import java.util.ArrayList;
import java.util.stream.Collectors;
public class PalindromeManager {
private static String str = "ehcache";
private static ArrayList<String> list = new ArrayList<>();
public static void main(String[] args) {
test(str);
String output = list.stream().collect(Collectors.joining());
System.out.println(output);
if (output.equals(str)) {
System.out.println("it was palindrome");
} else {
System.out.println("Nope! it wasn't");
}
}
private static void test(String str) {
if (str.length() <= 0) {
return;
}
String lastChar = "" + str.charAt(str.length() - 1);
list.add(lastChar);
test(str.substring(0, str.length() - 1));
}
}
2nd implementation using iteration -
public class PalindromeManager2 {
private static String str = "ehcache";
public static void main(String[] args) {
int startIndex = 0;
int lastIndex = str.length() - 1;
boolean result = true;
while (true) {
if (startIndex >= lastIndex) {
break;
}
char first = str.charAt(startIndex);
char last = str.charAt(lastIndex);
/*if (first == ' ') {
startIndex++;
continue;
}
if (last == ' ') {
lastIndex--;
continue;
}*/
if (first != last) {
result = false;
break;
}
startIndex++;
lastIndex--;
}
if (result) {
System.out.println("Yes! It was");
} else {
System.out.println("Nope! it wasn't");
}
}
}
In checkPalindrome method change the condition of for loop from i<baseball.length()-1 to i<baseball.length().

Categories