Writing a translator similar to pig latin - java

I'm writing a program in Java where I'm supposed to translate an English sentence to a language similar to pig Latin just with a few different rules.
So far I've written the code, but it only seems to translate one word at a time rather than a whole sentence. can you let me know where I went wrong? Heres my code:
import java.util.Scanner;
public class PartD {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a phrase to convert: ");
String phrase = keyboard.nextLine();
String[] words = phrase.split(" ");
for(int i = 0; i < words.length; i++ ) {
char firstLetter = (words[i].charAt(0));
if (firstLetter == 'a' || firstLetter == 'e' || firstLetter == 'i' || firstLetter == 'o' || firstLetter == 'u'){
String vowel = words[i] +"-eh";
System.out.print(vowel);
}else{
String start = words[i].substring(0,1);
String end = words[i].substring(1,phrase.length());
System.out.print(end + "-" + start + "eh" );
}
}
System.out.println( );
}
}

Related

How to get correct output for Pig Latin translator using JAVA

I am coding a JAVA application that translates english to pig latin. My application runs with no actual errors but the output is automatic and incorrect. This application will continue to run if the user selects "y".
Can you all see where my error lies?
Thank you.
CODE:
import java.util.Scanner;
public class PigLatin2 {
public static void main(String[] args) {
// create a Scanner object
Scanner sc = new Scanner(System.in);
// Run through the loop of calculations while user choice is equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("Enter a line to be translated");
System.out.println();
//Get String entered
String userInput = sc.toString();
//Line break
System.out.println();
String[] words = userInput.split(" ");
String output = "";
for(int i = 0; i < words.length; i++) {
String pigLatin = translated(words[i]);
output += pigLatin + " ";
}
System.out.println(output);
//Scan next line
sc.nextLine();
//line break
System.out.println();
// Ask use they want to continue
System.out.print("Continue? (y/n): ");
//Users choice
choice = sc.nextLine();
System.out.println();
}//END WHILE LOOP
//Close scanner object
sc.close();
}//END MAIN METHOD
private static String translated(String words) {
String lowerCase = words.toLowerCase();
int firstVowel = -1;
char ch;
// This for loop finds the index of the first vowel in the word
for (int i = 0; i < lowerCase.length(); i++) {
ch = lowerCase.charAt(i);
if (startsWithVowel(ch)) {
firstVowel = i;
break;
}
}
if (firstVowel == 0) {
return lowerCase + "way";
}else {
String one = lowerCase.substring(firstVowel);
String two = lowerCase.substring(0, firstVowel);
return one + two + "ay";
}
}
public static Boolean startsWithVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
}
This is the output I get automatically:
ava.util.scanner[delimiters=\p{javawhitespace}+][position=0][matchjay alid=false][needvay input=false][sourceway osed=false][skipped=false][groupclay eparator=\,][decimalsay eparator=.][positivesay efix=][negativepray efix=\q-\e][positivepray uffix=][negativesay uffix=][nansay ing=\qnan\e][infinitystray ing=\q?\e]stray

Java Replacing a Character with a Character

I am learning Java on my own and practicing using online exercises. I have only learned up until methods thus far so using an array for this exercise is beyond my scope, even though several solutions online use arrays to do what I want.
The exercise is this: Have the user enter a string with vowels. Wherever there is a vowel letter, display that vowel as a capital letter.
Example: If the user enters "apples", the correct output is ApplEs
I have this code so far:
import java.util.Scanner;
public class CapitalizeVowels {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string ~ ");
String string = keyboard.nextLine();
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
if (string.charAt(i) == 'a' ||
string.charAt(i) == 'e' ||
string.charAt(i) == 'i' ||
string.charAt(i) == 'o' ||
string.charAt(i) == 'u') {
char upperCaseVowel = Character.toUpperCase(string.charAt(i));
System.out.print(upperCaseVowel);
// need to replace string.charAt(i) with upperCaseVowel
// find something to replace characters
}
}
}
}
When I run my code as it is, with the input string "apples", for example, I get "aAppleEs" as my output. Both the lower case vowels and the upper case vowels are being printed. I am thinking that I should replace string.charAt(i) which is the lower case vowel with upperCaseVowel but I can't find any replace() method or something to that effect for characters. I tried other things like StringBuilder, etc. but I haven't come across a solution that is simple enough to avoid arrays as I didn't learn them yet. Any help on how I can get to the proper output is highly appreciated. Thanks!
Your mistake is printing every character before testing if it's a vowel.
Instead, print each char after you've figured out what it should be. The body of your loop should be:
char next = string.charAt(i);
if (next == 'a' ||
next == 'e' ||
next == 'i' ||
next == 'o' ||
next == 'u') {
next = Character.toUpperCase(next);
}
System.out.print(next);
You may consider adding:
else {
next = Character.toLowerCase(next);
}
To enforce non vowels being lower case.
You just need to move the Sysout prior to if statement to else, to avoid printing same character twice, e.g.:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string ~ ");
String string = keyboard.nextLine();
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == 'a' || string.charAt(i) == 'e' || string.charAt(i) == 'i' || string.charAt(i) == 'o'
|| string.charAt(i) == 'u') {
char upperCaseVowel = Character.toUpperCase(string.charAt(i));
System.out.print(upperCaseVowel);
// need to replace string.charAt(i) with upperCaseVowel
// find something to replace characters
}else{
System.out.print(string.charAt(i));
}
}
}
Try this, it works for me.
class ReplaceVowel {
public static void main(String[] args) {
String words = "apples";
char converted = 0;
String w = null;
for (int i = 0; i < words.length(); i++) {
if (words.charAt(i) =='a'|| words.charAt(i)=='e'||words.charAt(i)=='i'||words.charAt(i)=='o'||words.charAt(i)=='u') {
converted = Character.toUpperCase(words.charAt(i));
w = words.replace(words.charAt(i), converted);
words = w;
} else {
converted = Character.toUpperCase(words.charAt(i));
w = words.replace(words.charAt(i), converted);
words = w;
}
}
System.out.println(words);
}
}

Delivery is not working

In my java code the line String st = sc.nextLine(); is not taking input when the code is running and when instead I use sc.next(); the code works properly can you please tell me why sc.nextLine(); is not working
import java.lang.*;
import java.util.*;
/**?Chef wrote some text on a piece of paper and now he wants to know how
many holes are in the text. What is a hole? If you think of the paper as
the plane and a letter as a curve on the plane, then each letter divides
the plane into regions.For example letters "A", "D", "O", "P","R" divide
the plane into two regions so we say these letters each have one hole.
Similarly, letter "B" has 2 holes and letters such as "C", "E", "F","K"
have no holes. We say that the number of holes in the text is equal to
the total number of holes in the letters of the text.
Help Chef to determine how many holes are in the text.
Input
First line contains a single integer T <= 40, the number of test cases.
T test cases follow. The only line of each test case contains a non-empty
text composed only of uppercase letters of English alphabet. The length
of the text is less then 100. There are no any spaces in the input.
Output
For each test case,output a single line containing number of holes in the corresponding txt
Example
Input:
2
CODECHEF
DRINKEATCODE
Output:
2
5
*/
class Holes {
public static void main(String[] args) {
int i, Testcase;
int holes, space = 0, j;
Scanner sc = new Scanner(System.in);
Testcase = sc.nextInt();
for (i = 0; i < Testcase; i++) {
holes = 0;
space = 0;
String st = sc.nextLine();
if (st.length() < 100) {
char[] letter = st.toCharArray();
for (j = 0; j < st.length(); j++) {
if (letter[j] == ' ') {
space++;
}
}
for (j = 0; j < st.length(); j++) {
if (space == 0) {
if (letter[j] == 'A' || letter[j] == 'D'
|| letter[j] == 'O' || letter[j] == 'P'
|| letter[j] == 'R') {
holes = holes + 1;
}
if (letter[j] == 'B') {
holes = holes + 2;
}
}
}
}
if (st == st.toUpperCase() && space == 0) {
System.out.println(holes);
}
}
}
}
As Nighthacks mentioned, Scanner.nextInt will not advance to the next input (Read https://stackoverflow.com/a/13102066/643500)
Try it this way:
public class Holes {
public static void main(String[] args) {
int holes;
Scanner sc = new Scanner(System.in);
int numberOfCases = sc.nextInt(); // Get input as int - not going to
// advance
String[] testCases = new String[numberOfCases];
String line = sc.nextLine(); // Move to next
for (int i = 0; i < numberOfCases; i++) {
line = sc.nextLine();// Read input as line
testCases[i] = line;
}
sc.close();
for (String aCase : testCases) {
holes = 0;
if (aCase.length() < 100 && !aCase.contains(" ")) {
for (int j = 0; j < aCase.length(); j++) {
char letter = aCase.charAt(j);
if (letter == 'A' || letter == 'D' || letter == 'O'
|| letter == 'P' || letter == 'R') {
holes++;
}
if (letter == 'B') {
holes = holes + 2;
}
}
System.out.println(holes);
}
}
}
}
That's because the [Scanner#nextInt] method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Workaround:
Either fire a blank Scanner#nextLine call after Scanner#nextInt to consume rest of that line including newline
Check this out.

So I have this code here, it calculates the vowels in a given phrase. I'm trying to get it to repeat if the user says yes

I was wondering as to how I could get the end of the program to repeat if the user does respond with a 1. Do I need to reorganize it so that it is part of the if statement?
Scanner input = new Scanner(System.in);
System.out.println("Count Vowels \n============");
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int answer;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() + Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
if (answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
} else {
System.out.println("Have a nice day");
}
You can do this with a do/while loop. The skeleton for this kind of loop looks like this:
Scanner input = new Scanner(System.in);
do {
// do your stuff here
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
} while(input.nextInt() == 1);
System.out.println("Have a nice day");
It asks the user and evaluates the entered number in the while(input.nextInt() == 1) statement. If this comparison returns true (i.e. user entered 1), then the loops starts again. If not (i.e. user entered something else than 1), the loop stops and you'll get the "Good Bye" message instead.
you can split this up into more than one method and using one primary method call other methods inside a while loop. for example:
boolean continueCounting = false;
void countingVowels() {
//some start game method to make continueCounting = true
//something like "press 1 to start"
//if (input == 1) { continueCounting = true; }
while(continueCounting) {
String userInput = getUserInput();
countVowels(userInput); //count vowels in word from user input and prints them out to console
getPlayAgainDecision(); //ask user to put 1 or 2
if (answer == 1) {
continue
} else if (answer == 2) {
continueCounting = false;
} else {
System.out.println("incorrect input, please choose 1 or 2");
}
}
}
There are many ways to do this. A search on Google would have lead you to the correct answer in less time than it took you to ask the question. However, since you took the time to ask the question here is the answer:
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int answer = 0;
System.out.println("Count Vowels \n============");
// the do-while loop ensures that the code is executed at least once
do {
// on the first run answer equals zero, but on other runs it will equal one
if(answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
}
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i'
|| letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase()
+ Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? If so type 1 if not type 2 and press enter");
answer = input.nextInt();
} while (answer == 1);
System.out.println("Have a nice day");
}
}
In your code you assert that a letter is a vowel if it is in the set a, e, i, o and u which is true. However, the letter y can be a vowel in certain situations.
In general, the Y is a consonant when the syllable already has a vowel. Also, the Y is considered a consonant when it is used in place of the soft J sound, such as in the name Yolanda or Yoda.
In the names Bryan and Wyatt, the Y is a vowel, because it provides the only vowel sound for the first syllable of both names. For both of these names, the letter A is part of the second syllable, and therefore does not influence the nature of the Y.
You could expand on your code even more by checking if the letter y is a vowel or not.
This is a more elegant way to do the counting (I updated the code to satisfy Johnny's comment that my previous answer didn't answer OP's question. The code now loops without unnecessary code):
public static void main(String... args)
{
int answer = 0;
Scanner input = null;
do
{
input = new Scanner(System.in);
System.out.print("Type a sentence and this program will tell you\nhow many vowels there are (excluding 'y'):");
String sentence = input.nextLine();
int vowels = 0;
String temp = sentence.toUpperCase();
for (int i = 0; i < sentence.length(); i++)
{
switch((char)temp.charAt(i))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
}
}
System.out.println("The sentence: \"" + sentence + "\" has " + vowels + " vowels");
System.out.print("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press any other key... ");
String tempNum = input.next();
try
{
answer = Integer.parseInt(tempNum);
} catch (NumberFormatException e)
{
answer = 0;
}
System.out.println();
} while (answer == 1);
input.close();
System.out.println("Have a nice day");
}
Notice that at the end, I catch a NumberFormatException for more robustness validation of the user's input.
Just put the main for loop inside a do-while loop, like so:
do
{
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() +
Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
}
} while (answer == 1);
System.out.println("Have a nice day");
Additionally, there are better ways to do the counting, for example:
for (char c : string1.toCharArray())
{
c = Character.toLowerCase(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}

Code that needs to print a Scanner string without vowels

I need to write a program that takes a string, and prints out the string text with all the vowels removed, except when a word starts with it.
The code I've written is halfway there, but I cannot figure out why it will not return the whole string and it does not remove all the vowels. Say I input the phrase "Desirable property area". The program prints the string, "Dirlp" instead of "Dsrbl prprty ar "
Can anybody advise on how I can improve the code to make this work? Thank you!
Here is my code:
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter some text, then hit enter: ");
String text = in.nextLine();
takeOutVowel (text);
System.out.println ();
}
static void takeOutVowel (String s)
{
char ch = s.charAt(0); //character to be printed
System.out.print (ch);
int nextCh = 1; //determines the position of the next character
int increase = 1; //increase is how much i will increase by in the for loop; takes the position of vowels into //consideration so they can be skipped
for (int i = 1; i <= s.length(); i += increase)
{
ch = s.charAt (nextCh);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
nextCh++;
ch = s.charAt (nextCh);
while (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
{
nextCh++;
ch = s.charAt (nextCh);
if (nextCh >= s.length())
{
ch = ' ';
break;
}
}
}
System.out.print (ch);
nextCh++;
ch = s.charAt (nextCh);
if (ch == ' ') //if the previous position was a space, then this will allow for the vowel to be printed
{
System.out.print ("" + ch + s.charAt(nextCh + 1));
nextCh++;
}
increase = nextCh;
}
Thanks for all the answers so far - very helpful! I'm not allowed to use arrays or anything not covered yet, so I've amended the code to what it is below. It compiles fine but when I run the program and enter the Scanner text, I get a message that says
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 27
at java.lang.String.charAt(String.java:686)
at Vowels.noVowels(Vowels.java:20)
at Vowels.main(Vowels.java:11)
I can't figure what the problem is now. Thank you again for all the help!
import java.util.*;
class Vowels
{
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter some text, then hit enter: ");
String text = in.nextLine();
System.out.println (noVowels(text));
}
static String noVowels (String s)
{
String noVowels = "" + s.charAt(0); //Starts a new string with the first character of the input text
for (int i = 1; i <= s.length(); i++)
{
if (isVowel(s.charAt(i)) && s.charAt(i-1) != ' ') //if the character is a vowel and it's previous character wasn't a space, then this is a vowel to be replaced
{
noVowels = noVowels.concat("");
}
else
{
noVowels = noVowels.concat("" + s.charAt(i));
}
}
return noVowels;
}
static boolean isVowel (char ch)
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
return true;
}
else
{
return false;
}
}
}
You can solve this problem easily. Iterate over String and check the vowel. If no vowel than append the result. Try
static void takeOutVowel(String s) {
StringBuilder res = new StringBuilder();
String[] words = s.split(" +");
for (String word : words) {
res.append(word.charAt(0)); //Skip the first char
for (int i = 1; i < word.length(); i++) {
char ch = word.charAt(i);
if (!isVowel(ch)) { // Check the vowel
res.append(ch);
}
}
res.append(' ');
}
System.out.println(res);
}
static boolean isVowel(char ch){
ch=Character.toLowerCase(ch); // Make it case-insensitive.
return ch=='a' ||ch=='e' ||ch=='i' ||ch=='o' ||ch=='u';
}
You can do this easily with a regular expression as well. The first example demonstrates how to simply remove vowels.
public static void main(String[] args)
{
String noVowels = takeOutVowel("Hello how are you?");
System.out.println(noVowels); // prints "Hll hw r y?"
}
// This will remove all vowels from any String
private static String takeOutVowel(String s)
{
return s.replaceAll("[aeiou]", "");
}
But now to satisfy your requirement of ignoring the first letter of a word if it is a vowel (which means we will ignore it no matter what), you just need to edit the takeOutVowel method a bit.
static String takeOutVowel (String s)
{
// split your string so we can examine each word separately
String[] words = s.split(" ");
String noVowels = "";
for (int i = 0; i < words.length; i++){
char firstChar = words[i].charAt(0);
String temp = words[i].substring(1, words[i].length()).replaceAll("[aeiou]", "");
noVowels += firstChar + temp + " ";
}
return noVowels;
}
This works for your following requirement - Remove all vowels except for when the word starts with a vowel.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter some text, then hit enter: ");
String text = in.nextLine();
takeOutVowel(text);
System.out.println();
}
static void takeOutVowel(String s) {
String[] array = s.split(" "); // Split sentence into words and store them in an array.
StringBuilder finalString = new StringBuilder();
for (String word : array) { //For each word in the array
char ch = word.toLowerCase().charAt(0); //check if the lower case first character is a vowel.
if(ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u'){ // When it is not, replace all the vowels.
finalString = finalString.append(word.replaceAll("[aeiou]", "")).append(" ");
}else{
finalString = finalString.append(ch).append(word.replaceAll("[aeiou]", "")).append(" ");// When it is , replace all the vowels except the first character.
}
}
System.out.println(finalString);
}
}

Categories

Resources