Java Pig Latin Converter is spitting out an extra word - java

I'm working on a project for my Programming Applications course with WGU. I've decided to adapt a python-based pig latin converter from the previous course. I've almost got it done, but when I run the program, I get an extra word. For example, if I enter Latin, it prints atinLay, then on the next line, prints inLatay.
I'm not sure which part of the code is causing this. I know it should be a simple fix but I just can't find it. Here is my code:
import java.util.Scanner;
public class PigConverter
{
public static void main(String[] args)
{
Scanner anscay = new Scanner(System.in);
System.out.print("Enter a word:");
String word = anscay.nextLine();
System.out.println("This word, in pig latin, would be:");
String pigConvert;
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')
{
String second = word.substring(0,i);
String first = word.substring(i,word.length());
System.out.println(first+second+"ay");
}
}
}
}

I think that your loop is finding BOTH vowels in the word, so it/s doing the output twice. I think that your loop should break once you find the first vowel.

Related

debug : Trouble shooting Backwards triangle project

I don’t understand why this doesn’t run. I am trying to make a program that displays the text the user inputs as a triangle.
Each new line adds a letter which forms the triangle pattern.
For example, if the user enters the word computers, the output would be:
s
sr
sre
sret
sretu
sretup
sretupm
sretupmo
sretupmoc
import java.util.Scanner;
public class BackwordsTri
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
String newWord="";
char ch;
int wl = word.length();
for (int i=0; i < word.length(); i++)
{
int q = (wl - i);
ch= word.charAt(q);
newWord= ch + newWord;
System.out.println(newWord);
}
}
}
We might need a little more information to help you out on this one. It sounds like you want to be able to print the reversed version of the user input, incrementing by 1 additional letter per line starting from the last letter of the word.
Would you be able to add in the error that you are getting or what the output is from your program? along with a formatted version of the expected output if the issue is in fact formatting?

Pig latin Java program with try-catch, translation passed though function

I am making a java program that translates a sentence to pig latin. I need to have at least one try-catch in this program and the translation must be done in a function. The original word will be passed to this function and return the translated word back to the function call per my professor's wishes. I am also having trouble asking the user if they want to translate something else. even when I say no it still restarts the program.
this is what I have:
package midtermPigLatin;
import java.util.Scanner;
import textio.TextIO;
public class midtermPigLatin {
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
String yourSentence="";
boolean again = true;
try {
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();
System.out.println("Do you want to play again, Yes or no");
again = TextIO.getBoolean();
} while(!yourSentence.equals("quit"));
}catch(Exception errMsg)
{
System.out.print(" error" + errMsg);
}
}
}
I just need help modifying my program to pass the translation through a function original word will be passed to this function and return the translated word back to the function call and the ending the program if user says no.
Here is what I get when I run the program:
Enter your words here: apple door shave
appleway oorday aveshay
Do you want to play again, Yes or no
no
Enter your words here:

Palindrome parser logic error

I'm trying to create a program that parses through an input and determines whether or not it is a palindrome. Pasted below is my code so far:
import java.util.Scanner;
//Gets a message and shift amount and caesar shifts the message by the desired amount. Displays the enciphered message.
public class RobustPalChecker{
public static void main(String[] args){
//declare variables
char current, currentReverse;
int msgInt;
String msg, msgReverse;
StringBuffer sbMsg, newMsg;
Scanner sc = new Scanner(System.in);
//get message
System.out.println("Please enter an integer: ");
msg = sc.nextLine().toUpperCase();
//msgReverse = new StringBuffer(msg).reverse().toString();
System.out.println(msg);
//System.out.println("= " + msgReverse);
//get first and last index of string to check if it's a palindrome
for(int i = 0; i < msg.length(); i++) {
current = msg.charAt(i);
if(Character.isLetter(current) == false){
sbMsg = new StringBuffer(msg);
newMsg = sbMsg.deleteCharAt(i);
msgReverse = new StringBuffer(newMsg).reverse().toString();
}
}
if(newMsg.equals(msgReverse)) {
System.out.println("It's a palindrome");
}else {
System.out.println("It's not a palindrome");
}
}
}
Ignore comments as some of them don't apply and I have not cleaned it up yet. The line of code that I'm pretty sure is causing the error is the isLetter line. The goal of that loop is to find any character that is not a letter and just delete it, and that includes whitespace. That last if statement is the one that actually compares the reversed string and regular string. Now the output that the last if statement is giving me when I try to compile is "variable newMsg might not have been initialized" and the same for msgReverse, but that's not my main question.
My main question is: Is my logic here correct or incorrect?
Also, if you need me to rephrase the question, I can do that as I understand this might be hard to follow, I'm just panicking a little.
Your logic seems fine, but since code is not at all upto the mark its difficult to verify. I have written code in english commented format, if you are able to fill in the blanks all will fall in place.
Let's breakdown the problem in two sections :
Remove unwanted characters from string
Check if string returned from step1 is a pallindrome.
Create two functions :
String cleanUp(String arg){
//create a stringbuffer from arg
//start for loop
//delete unwanted chars from stringbuffer
//end loop
//make string from stringbuffer and return
}
boolean pallindrome(String arg){
//create a new string from arg reverse
//return true if reversed string and arg are same
}
Now call these functions from your main method.

writing a translator similar to pig latin in java

So far I've been trying to write a program that's supposed to translate an English sentence to a language similar to pig Latin. Here's what the question looks like.
You will write a translator English to DrA’s TwinSpeak. Twins often make up a language that others can’t understand. It’s a secret code. It’s sort of like Pig Latin, but all twins make up their own rules.
A word that starts with a vowel has "-eh" added to the end.
Egg becomes egg-eh, open becomes open-eh, ultimate becomes ultimate-eh.
A word that starts with a single consonant, will have the consonant moved to the end of the word, then add the ‘eh’ word becomes ord-weh, mainly becomes ainly-meh
A word that starts with 2 or 3 consonants does not get changed at all.
Spain remains Spain. Three remains three.
and this is what I'm supposed to translate:
The rain in Spain stays mainly on the plain but the ants in France stay mainly on the plants
this is supposed to become like this:
The ain-reh in-eh Spain stays ainly-meh on-eh the plain ut-beh the ants-eh in-eh France stay ainly-meh on-eh the plants
I've written the code, however, it only seems to translate one word at a time rather than the whole sentence. if i translate the whole sentence, i get an error message.
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( );
}
}
This line:
String end = words[i].substring(1,phrase.length());
is using the length of the entire initial string.
You want the length of the word you parsed, eg
String end = words[i].substring(1,words[i].length());
Also, add a space to each word you create to break up the result, eg
String vowel = words[i] +"-eh "; // note the added space

Space Replacement for Float/Int/Double

I am working on a class assignment this morning and I want to try and solve a problem I have noticed in all of my team mates programs so far; the fact that spaces in an int/float/double cause Java to freak out.
To solve this issue I had a very crazy idea but it does work under certain circumstances. However the problem is that is does not always work and I cannot figure out why. Here is my "main" method:
import java.util.Scanner; //needed for scanner class
public class Test2
{
public static void main(String[] args)
{
BugChecking bc = new BugChecking();
String i;
double i2 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (i2 <= 0.0)
{
i = in.nextLine();
i = bc.deleteSpaces(i);
//cast back to float
i2 = Double.parseDouble(i);
if (i2 <= 0.0)
{
System.out.println("Please enter a number greater than 0.");
}
}
in.close();
System.out.println(i2);
}
}
So here is the class, note that I am working with floats but I made it so that it can be used for any type so long as it can be cast to a string:
public class BugChecking
{
BugChecking()
{
}
public String deleteSpaces(String s)
{
//convert string into a char array
char[] cArray = s.toCharArray();
//now use for loop to find and remove spaces
for (i3 = 0; i3 < cArray.length; i3++)
{
if ((Character.isWhitespace(cArray[i3])) && (i3 != cArray.length)) //If current element contains a space remove it via overwrite
{
for (i4 = i3; i4 < cArray.length-1;i4++)
{
//move array elements over by one element
storage1 = cArray[i4+1];
cArray[i4] = storage1;
}
}
}
s = new String(cArray);
return s;
}
int i3; //for iteration
int i4; //for iteration
char storage1; //for storage
}
Now, the goal is to remove spaces from the array in order to fix the problem stated at the beginning of the post and from what I can tell this code should achieve that and it does, but only when the first character of an input is the space.
For example, if I input " 2.0332" the output is "2.0332".
However if I input "2.03 445 " the output is "2.03" and the rest gets lost somewhere.
This second example is what I am trying to figure out how to fix.
EDIT:
David's suggestion below was able to fix the problem. Bypassed sending an int. Send it directly as a string then convert (I always heard this described as casting) to desired variable type. Corrected code put in place above in the Main method.
A little side note, if you plan on using this even though replace is much easier, be sure to add an && check to the if statement in deleteSpaces to make sure that the if statement only executes if you are not on the final array element of cArray. If you pass the last element value via i3 to the next for loop which sets i4 to the value of i3 it will trigger an OutOfBounds error I think since it will only check up to the last element - 1.
If you'd like to get rid of all white spaces inbetween a String use replaceAll(String regex,String replacement) or replace(char oldChar, char newChar):
String sBefore = "2.03 445 ";
String sAfter = sBefore.replaceAll("\\s+", "");//replace white space and tabs
//String sAfter = sBefore.replace(' ', '');//replace white space only
double i = 0;
try {
i = Double.parseDouble(sAfter);//parse to integer
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println(i);//2.03445
UPDATE:
Looking at your code snippet the problem might be that you read it directly as a float/int/double (thus entering a whitespace stops the nextFloat()) rather read the input as a String using nextLine(), delete the white spaces then attempt to convert it to the appropriate format.
This seems to work fine for me:
public static void main(String[] args) {
//bugChecking bc = new bugChecking();
float i = 0.0f;
String tmp = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (true) {
tmp = in.nextLine();//read line
tmp = tmp.replaceAll("\\s+", "");//get rid of spaces
if (tmp.isEmpty()) {//wrong input
System.err.println("Please enter a number greater than 0.");
} else {//correct input
try{//attempt to convert sring to float
i = new Float(tmp);
}catch(NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
System.out.println(i);
break;//got correct input halt loop
}
}
in.close();
}
EDIT:
as a side note please start all class names with a capital letter i.e bugChecking class should be BugChecking the same applies for test2 class it should be Test2
String objects have methods on them that allow you to do this kind of thing. The one you want in particular is String.replace. This pretty much does what you're trying to do for you.
String input = " 2.03 445 ";
input = input.replace(" ", ""); // "2.03445"
You could also use regular expressions to replace more than just spaces. For example, to get rid of everything that isn't a digit or a period:
String input = "123,232 . 03 445 ";
input = input.replaceAll("[^\\d.]", ""); // "123232.03445"
This will replace any non-digit, non-period character so that you're left with only those characters in the input. See the javadocs for Pattern to learn a bit about regular expressions, or search for one of the many tutorials available online.
Edit: One other remark, String.trim will remove all whitespace from the beginning and end of your string to turn " 2.0332" into "2.0332":
String input = " 2.0332 ";
input = input.trim(); // "2.0332"
Edit 2: With your update, I see the problem now. Scanner.nextFloat is what's breaking on the space. If you change your code to use Scanner.nextLine like so:
while (i <= 0) {
String input = in.nextLine();
input = input.replaceAll("[^\\d.]", "");
float i = Float.parseFloat(input);
if (i <= 0.0f) {
System.out.println("Please enter a number greater than 0.");
}
System.out.println(i);
}
That code will properly accept you entering things like "123,232 . 03 445". Use any of the solutions in place of my replaceAll and it will work.
Scanner.nextFloat will split your input automatically based on whitespace. Scanner can take a delimiter when you construct it (for example, new Scanner(System.in, ",./ ") will delimit on ,, ., /, and )" The default constructor, new Scanner(System.in), automatically delimits based on whitespace.
I guess you're using the first argument from you main method. If you main method looks somehow like this:
public static void main(String[] args){
System.out.println(deleteSpaces(args[0]);
}
Your problem is, that spaces separate the arguments that get handed to your main method. So running you class like this:
java MyNumberConverter 22.2 33
The first argument arg[0] is "22.2" and the second arg[1] "33"
But like other have suggested, String.replace is a better way of doing this anyway.

Categories

Resources