Pig Latin String Encryption - java

I am writing a program that takes a string, splits it into words, converts the words into pig latin, and then returns the result string. I have it working to a certain point.
For example if I enter these words that do not start with a vowel into the program I get:
pig -> igpay
trash -> rashtay
duck -> uckday
(for words that do not start with vowels, they have their first letter removed, added to the end of the word along with "ay")
It also works when the word starts with a vowel (just take the word and add "yay" to the end).
For example if I enter these words into the program I get:
eat -> eatyay
areyay -> areyay
omelet -> omeletyay
Now the issue I am having is if I combine 2 words, one that starts with a vowel and one that doesn't, it prints out both like they both start with vowels.
For example if I enter these words into the program I get:
pig -> pigyay (should be igpay)
eat -> eatyay (correct)
It might be worth mentioning that the methods "isVowel" & "pigLatinEncrypt" are required to have in this program. Please disregard the other methods that are in the program.
public static void main(String[] args) {
// TODO code application logic here
String input, message;
int ans1, ans2, key;
input = JOptionPane.showInputDialog("1. to decrypt a message\n2. to encrypt a message");
ans1 = Integer.parseInt(input);
input = JOptionPane.showInputDialog("1. for an entire message reversal encryption\n"
+ "2. for a Pig-Latin encryption\n3. for a simple Caesar style encryption");
ans2 = Integer.parseInt(input);
if (ans2 == 3) {
input = JOptionPane.showInputDialog("Please enter a key for encryption");
key = Integer.parseInt(input);
}
input = JOptionPane.showInputDialog("Please enter the message to encrypt or decrypt");
message = input;
if (ans2 == 1) {
reverseEncryptandDecrypt(message);
}
if (ans2 == 2) {
String[] words = message.split(" ");
if (ans1 == 2) {
boolean isVowel = isVowel(words);
pigLatinEncrypt(words, isVowel);
}
if (ans1 == 1) {
pigLatinDecrypt(message);
}
}
}
public static void reverseEncryptandDecrypt(String message) {
char[] stringToCharArray = message.toCharArray();
System.out.print("You entered the message: ");
for (char c : stringToCharArray) {
System.out.print(c);
}
int i = stringToCharArray.length - 1, j = 0;
char[] reverse = new char[stringToCharArray.length];
while (i >= 0) {
reverse[j] = stringToCharArray[i];
i--;
j++;
}
System.out.print("\n\nThe result is: ");
for (char c : reverse) {
System.out.print(c);
}
System.out.println();
}
public static void pigLatinEncrypt(String[] words, boolean isVowel) {
for (String word : words) {
if (isVowel == true) {
System.out.print(word + "yay ");
} else {
System.out.print(word.substring(1) + word.substring(0, 1) + "ay ");
}
}
}
public static boolean isVowel(String[] words) {
boolean isVowel = false;
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o")
|| word.startsWith("u")) {
isVowel = true;
}
}
return isVowel;
}
}

This method:
public static void pigLatinEncrypt(String[] words, boolean isVowel)
takes an array of words and a single isVowel boolean. Thus, if there is more than one word, and some, but not all, of them begin with vowels, there's no way to tell the method that.
You'll need to change the method definition. Either it should take only one word String (simplest), or it needs to take an array of isVowel booleans that correspond to the array of word
Edit: When I wrote this, I didn't look carefully at the rest of your code. But the isVowel method has the same problem: it takes an array of words, but returns a single boolean. This can't work, for the same reason--if some of the words start with vowels and some don't, what would the method return?
If you can make the isVowel method take a single String argument, that would be simplest. Then you'd call it multiple times. If you want to make isVowel return a boolean[], the method would do something like
boolean[] result = new boolean[words.length];
to create an array of boolean that has the same number of elements as words.

Related

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

Need help checking for white-space in If/else statements in Java

I am new to learning java and I'm doing a project for my online class and currently stuck on part of it.
Write a program that checks the properness of a given variable name. More specifically, your program should specify whether a user-entered variable name is:
illegal (no spaces allowed, must begin with a letter)
legal, but uses poor style (should only use letters or digits)
good
You don’t need to check for an uppercase letter for the first letter in the second word, third word, etc.
So my problem is that since having space in a variable name is illegal, I need to check the user's input for space, and if there is one it needs to print that it is illegal. I also need to check for special symbols (like $%#) and if it is anywhere but the first character, have it print that it is legal but improper.
I feel like this is super simple I just can't figure it out.
import java.util.Scanner;
public class IdentiferCheck
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
String variableName = "";
char ch = ' '; //temp holder
//Get User Input
System.out.println("This program checks the properness of a proposed Java variable name.");
System.out.println("Please enter a variable name (q to quit):");
variableName = in.nextLine();
//Check if variable name is proper
do
{
//Check if first char is lowercase
ch = variableName.charAt(0);
if (Character.isLetter(ch) && Character.isLowerCase(ch))
{
System.out.println("Good!");
}
else if (Character.isDigit(ch) && Character.isUpperCase(ch) && variableName.contains(" "))
{
System.out.println("Illegal!");
}
//Allow user to input another name or quit
System.out.println("Enter another name or press q to quit: ");
variableName = in.nextLine();
} while (!variableName.equalsIgnoreCase("q"));
}
}
make sure to read the following documentation for your task. It's worth noting that the requirements don't actually match the real world requirements of Java variable names. However, the most difficult part of this task is the logic rather than the script. I've written an example script for you below:
Subsequent characters may be letters, digits, dollar signs, or underscore characters. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
import java.util.Scanner;
public class identifierCheck
{
public static void main(String[] args) {
String input = " ";
System.out.printf("type q to exit...\n");
while (input.charAt(0) != 'q' && input.length() == 1) // Note the length so that you can use q for starting variable names
{
input = requestLine();
if (checkValid(input))
{
System.out.printf("%s is legal...\n", input);
}
}
}
public static String requestLine()
{
Scanner cmd = new Scanner(System.in);
System.out.printf("Enter a variable name > ");
return cmd.nextLine();
}
public static boolean startsWithLetter(String input)
{
if (123 > (int)input.toLowerCase().charAt(0) && (int)input.toLowerCase().charAt(0) > 60)
{
return true;
}
else
{
return false;
}
}
public static boolean containsInvalid(String input)
{
if ((input.indexOf('$') != -1 || input.indexOf('_') != -1) && input.indexOf(' ') == -1)
{
System.out.printf("Using $ and/or _ in variable names is poor style...\n");
}
if (input.indexOf(' ') != -1) // Has a space in the string
{
return true;
}
else
{
return false;
}
}
public static boolean checkValid(String input)
{
if (!startsWithLetter(input))
{
System.out.printf("%s is illegal, must start with a letter (note: $ and _ are 'valid' to start variable names)...\n", input);
return false;
}
else if (containsInvalid(input))
{
System.out.printf("%s is illegal, it must not contain spaces...\n", input);
return false;
}
else
{
return true;
}
}
}
Good luck with your course! Java's an excellent language to learn.

Java - word scrambler [keeping first and last letter]

My assignment is to write a program to scramble a word while maintaining the same first and last letter and only swapping two letters, then prompt the user to continue if they wish.
Example: userInput = bacon | Output = bcaon
I've attached an imagine of my program, there may be several issues, but as it stands I can't really run it due to the errors in the image. I'm really confused because I got a TA to help me on this assignment, and they seemed to think this would definitely work, but as you can see it does not.
I would really appreciate if someone could tell me what exactly is wrong and why. And if you have anything to add to make this program work, I'd really, really appreciate that too, but bottom line is I just want to understand what's wrong and why.
import java.util.Scanner;
import java.util.Random;
public class FreeStyle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // Importing and initializing keyboard to 'in'
System.out.println("Please enter a word to be scrambled"); // Asking user for a word
String word = in.next(); // Initializing the user's input
System.out.println(swapLetters(word));
System.out.println("Would you like to enter another word? y/n");
String answer = in.next();
boolean userDone = true; //Using a Boolean statement to ask the user if they are done enter words or not
while (userDone) {
if (answer.equals('y')) {
System.out.println("Please enter a new word"); //Ask user for new word to scramble
word = in.nextLine(); //New initialization for 'word'
} else if (answer.equals('n')) { //If user types 'n', loops then breaks because while(userDone) is false
userDone = false;
} else {
System.out.println("Invalid input, please enter more than 3 letter words."); // The logic doesn't flow or apply to words that are less than 4 letters, so this catches that error and notifies the user
}
}
}
private static String swapLetters(String word) { //Private method used for the program only, no need to involve the user
Random r = new Random(); //Using random instead of math floor
//int arraysize = word.length();
int a = r.nextInt(word.length()-2)+1;
int b = r.nextInt(word.length()-2)+1;
//String word2 = word.substring(a, a+1);
String word2 = word.substring(0, a) + word.charAt(b)+word.substring(a+1, b)+word.charAt(a)+word.substring(b+1);
return word2;
}
Several points:
Why not use something already done exactly for what you are trying to do - Collections.shuffle? See comments in the code for understanding how it works.
You can't use equals() between a String and a char (' ' are for chars, " " are for Strings). Simple fix - just put your 'y' into "y", same for 'n'.
I've refactored the code at the beginning that we used to get user input and then scramble into a separate method, so we can reuse it again - getInputAndScramble.
And finally, I've used a do-while loop to keep looping until the user stops the loop with the "n" letter.
Please see my comments in the code, hopefully will clear things up.
public class Scrambler {
public static void main(String[] args) {
boolean userDone = true;
String word;
Scanner in = new Scanner(System.in);
getInputAndScramble(in); //Extracted method to get Scanner input and scramble
do {
System.out.println("Would you like to enter another word? y/n");
word = in.next();
while (userDone) {
if (word.equals("y")) {
getInputAndScramble(in);
break;
} else if (word.equals("n")) {
userDone = false;
} else {
System.out.println("Invalid input, please enter more than 3 letter words.");
}
}
} while (userDone); //continue until "n"
}
private static void getInputAndScramble(Scanner in) {
System.out.println("Please enter a word to be scrambled");
String word = in.next();
System.out.println(swapLetters(word));
}
private static String swapLetters(String word) {
/* Convert word into an ArrayList of characters.
Create ArrayList size of word,
convert String word into a char array and insert every char in
the char array into our ArrayList.
*/
ArrayList<Character> chars = new ArrayList<>(word.length());
for (char c : word.toCharArray()) {
chars.add(c);
}
//Shuffle, omitting first and last letters
Collections.shuffle(chars.subList(1, chars.size()-1));
//Add shuffled letters into an array to output as a word entity
char[] shuffled = new char[chars.size()];
for (int i = 0; i < shuffled.length; i++) {
shuffled[i] = chars.get(i);
}
//Return shuffled String
return new String(shuffled);
}
}
You are assuming that the two random number a and b have the property that a < b. What if a >= b? Then word.substring(a+1, b) will throw an error.
To fix it, just make sure that a < b is maintained (regenerating, swapping, etc.).
But to be sure, there are more than just this bug in your code. For example, using next(), comparing String with char, using wrong newline character, not striping newline character, and so on. You might want to add some print statements in your code you see what is actually happening.
Well, as for the swapping function, something like that should work:
private static String swapLetters(String word) {
char[] temp = word.toCharArray();
char swapHelper;
Random r = new Random();
int a = r.nextInt(word.length()-2)+1;
int b = r.nextInt(word.length()-2)+1;
swapHelper = temp[a];
temp[a] = temp[b];
temp[b] = swapHelper;
word = String.copyValueOf(temp);
return word;
}
Basically, im converting string to char array so i can operate on them with ease. A and B are variables that contain index of letters that should be swapped. After that, array is converted back to string and returned.

checking if first char is equal to last char

I'm fairly new to java and I was wondering on how to return my code to false if the 1st and last letter aren't the same
he whole instruction was to define and test a method called checkString that will take in the word as a parameter and checks whether the String begins and ends with the same letter. If both letters are the same the method returns true otherwise false (returns a boolean). The program treats lower and uppercase letters as equivalent
here's what I have:
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
System.out.printf ("%s begins and ends with the same letter.", checkString(word));
}
public static boolean checkString (String word) {
int stringLength = word.length();
String letter1 = (word.substring (0,1)).toUpperCase();
String lastletter = (word.substring ((stringLength-1),(stringLength))).toUpperCase();
if (letter1.equals(lastletter)){
return true;
} else {
return false;
}
}
}
As per your code; instead of:
if (letter1.equals(lastletter)) {
return true;
} else {
return false;
}
Just do:
return letter1.equals(lastletter);
However your checkString() {...} code should be:
public static boolean checkString (String word) {
int len = word.length();
word = word.toUpperCase(); //since you are testing them as upper case
char firstLetter = word.charAt(0);
char lastLetter = word.charAt(len - 1);
return firstLetter == lastLetter;
}
Also instead of:
System.out.printf (word + " begins and ends with the same letter.", checkString(word));
Use print():
System.out.print(word + " begins and ends with the same letter: " + checkString(word));
Edit:
If you want to use printf() try something like:
System.out.printf("%s begins and ends with the same letter. %s", word , checkString(word));
%s is like a place holder for word and the value returned by checkString(word).
You could do the following:
public boolean firstAndLast(String word)
{
return Character.toUpperCase(word.charAt(0)) == Character.toUpperCase(word.charAt(word.length()-1));
}
This checks the positions of 0 and length - 1 to see if they're equal to each other. If they are, it returns true, if not, false.
If you want to one-line it:
return (word.substring (0,1)).toUpperCase().equals(word.substring(word.length()-1).toUpperCase());
Before the .equals(...) it fetches the first character, converts it to one case, doesn't matter which one as long as you are using the same case later on.
word.substring(string.length()-1).toUpperCase();
Fetches the last key and converts it to upper case.
This is how I would write it most likely
private boolean isFirstAndLastEqual (String word) {
char first = Character.toUpperCase(word.charAt(0));
char last = Character.toUpperCase(word.charAt(word.length()-1));
return first == last;
}
You do not need such a complicated code.
Here is a very simple written method that does the work perfectly.
Code
public static boolean checkString (String word) {
return word.toLowerCase().charAt(0) == word.toLowerCase().charAt(word.length()-1);
}
Explaination
It compares the first and the last character of the String input put to lowercase so that it matches the lower and uppercases.
Your use of printf is wrong as you are not printing out the true/false value. Either add a boolean specifier to your output string or use println instead.
System.out.printf (word + " begins and ends with the same letter - %b\n", checkString(word));
System.out.println (word + " begins and ends with the same letter " + checkString(word));
You could do the following
public static boolean checkString(final String word) {
final String checkedString = word.toLowerCase();
final char[] chararray = checkedString.toCharArray();
if (chararray.length > 1) {
return chararray[0] == chararray[chararray.length-1];
} else {
return true;
}
}
This will convert the String to lower case. (You could also achieve this with word.toUpperCase();) After that the String is converted to a char Array and then checks the first and the last "char". if the given String is of length "0" then true will be returned. Depending on how you want to decide for emtpy Strings you could also change this to false
This should give you what you're looking for.
This gets the first letter (character at index 0): firstletter = (word.charAt(0)).toUpperCase();
This gets the last letter: firstletter = (word.charAt(0)).toUpperCase();The last character is at index word.length-1. For example, if your word is "apple", it has a length of 5, but the last character is at index 4 (remember, 0-4 not 1-5; letter1 is misleading, it's actually letter0).
As mentioned by Savior Self, using charAt is more efficient. Also, being that you'd use char's rather than String's and == to compare them.
Also, you would assign the return value to a variable when you call checkString. For instance, boolean checkStr = checkString(word); and then use checkStr in your print statement.
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
boolean checkStr = checkString(word);
System.out.println(word + " begins and ends with the same letter: " + checkStr;
}
public static boolean checkString (String word) {
char firstletter = (word.charAt(0)).toUpperCase();
char lastletter = (word.charAt(word.length-1)).toUpperCase();
return (firstletter == lastletter);
}
}
Also, since I don't have enough points to comment, a better one-liner would be:
return (word.charAt(0)).toUpperCase() == (word.charAt(word.length-1)).toUpperCase());

How to pass a char array to a method and return a boolean value

I am trying to write a program which checks whether a word is a palindrome or not. My code compiles butthe code in the isItPalindrome method doesn't seem to be run at all. I'm hoping someone can point out where i have gone wrong. Here is my code:
class Main
{
public static void main ( String args[] )
{
System.out.print ("#Enter word");
String word = BIO.getString();
String wordLowerCase = word.toLowerCase(); // converts word to lower case (only way i could think of to ignore case)
char letters[] = wordLowerCase.toCharArray(); // converts string into an array of character
while ( !word.equals ("END")){
if (isItPalindrome(letters) == true)
{
System.out.print (""+word+"");
System.out.println (" is a palindrome");
}
else if (isItPalindrome(letters) == false)
{
System.out.print (""+word+"");
System.out.println (" is not a palindrome");
}
System.out.print ("#Enter word");
word = BIO.getString();
}
}
public static boolean isItPalindrome ( char letters[]){
boolean palindrome = true;
if (letters.length%2 == 0){
for (int index=0; index<letters.length/2-1; index++) //index will finish at letters/2
{
if (letters[index] != letters[letters.length-index-1]) //checks if index is the same as its opposite letter
{
return false;
}
else //if any pairs of letters are not in ascending order then it returns fasle and breaks out of the loop
{
palindrome = true;
}
}
}
else{
for (int index = 0; index < (letters.length-1)/2-1; index++)
{
if (letters[index] != letters[letters.length-index-1]){
return false;
}
else{
palindrome = true;
}
}
}
return palindrome;
}
}
There were some issues in the main-method, for example the char-array was never updated and the palindrome-method was far to complicated, here is the working version:
public static void main(String args[]) {
System.out.print("#Enter word: ");
String word = BIO.getString();
while (!word.equals("END")) {
char[] letters = word.toLowerCase().toCharArray();
if (isItPalindrome(letters) == true) {
System.out.println(word + " is a palindrome");
} else {
System.out.print(word + " is not a palindrome");
} // OR
// Use this one-liner instead of the if:
// System.out.println(word + isItPalindrome(letters) ?
// " is a palindrome" : " is not a palindrome");
System.out.print("#Enter word: ");
word = BIO.getString();
}
}
public static boolean isItPalindrome(char letters[]) {
for (int i = 0; i < letters.length / 2; i++) {
if (letters[i] != letters[letters.length - i - 1]) {
return false;
}
}
return true;
}
Hope this helps.
Besides the initial word, your character array letters never reflects the current word in your while loop inside your main method. I don't know what you mean when you say your method "doesn't seem to be run at all" but I assume that you meant it's being run with the wrong output. This is one reason why. Be sure to call
wordLowerCase = word.toLowerCase();
letters = wordLowerCase.toCharArray();
every iteration of the while loop.
Side note: In your isItPalindrome method, you do not even need any of the else statements or the boolean palindrome at all. Simply return false if you ever find a case when the word is not a palindrome like you currently are. Then, if you have gotten to the end of the word, it must be a palindrome and you can return true.
First, to answer the question that's in the title:
public boolean palindrome(char C)
Has a return type of boolean but requires that you pass it a Character.
Second:
You're over-complicating things in the way that you reverse the words to check them. You could simply take the word, as a String, and take it apart, putting it into an array of Characters. Then put each char variable into a Stack. Then as you take them out of the stack, piece by piece, copy them to another array of Characters.

Categories

Resources