Question

In: Computer Science

Lab 12 - If y cn rd ths, y cn b a gd prgrmmr. In this...

Lab 12 - If y cn rd ths, y cn b a gd prgrmmr.

In this lab, you will explore String manipulation by removing characters from Strings. Even with many characters removed, it is still possible too get the meaning. While this isn’t exactly lossy compression, it does show you that even with information removed, you can still understand what you are looking at even if the quality is not the same.

Step 0: Constant

Create a public static final String called VOWELS at the topic of your class. Initialize it to “aeiouAEIOU”. You will use this later.

Step 1: lettersAndWhitespaceOnly(String)

For this method, you will take in a message, and keep only letters and whitespace. Everything else (numbers, punctuation, etc) will be removed. So for example

String value = lettersAndWhitespaceOnly("The number 42 is a number that is popular due to Hitchhikers Guide to the Galaxy.")

would set value equal to

"The number  is a number that is popular due to Hitchhikers Guide to the Galaxy"

While

String value = lettersAndWhitespaceOnly("!@!(*&(*&)!(!x*@)9191828101")

would set the value equal to

"x"

Writing lettersAndWhitespaceOnly

For this method, we already gave you the method stub, so you will only need to write a loop.

To help the loop conditions are from 0 to the length of the String, so as follows:

for(int i = 0; i < message.length(); i++) {
   // do something here
}

You will then want to check the character at that location, to see if it is a letter or whitespace and if it is, add it too the return string.

Some helpful methods are:

  • .charAt(index)
  • Character.isWhitespace(char)
  • Character.isLetter(char)
  • Zybooks Chapter on Character

Step 2: removeWhiteSpace(String)

For this method, you will take in a message, and remove all whitespace from the message. Imeanwecanallreadwithoutwhitespace - ok, let’s try that again. We can all read without whitespace.

In either case, this is a nice warm up, that will help for the other methods.

Writing removeWhiteSpace(String)

You will start off with a very similar loop as the last method, and instead of looking for whitespace and letters - you will only need to look for whitespace. The difference is:

  • If you find whitespce - DON’T Add it to the return String
  • everything else, add it!

Step 3: hasCharacter(char, String)

This is your first helper method for the lossy compression, and will make it easier to work getting this one right. The goal is to take a character, and check to see if that character is in a group of characters. For example, is x in the AeiOu? You know that it isn’t, so the method should return false.

Start thinking of ways that you can solve this problem, and then you can start writing after you get an idea.

Writing hasCharacter(char, String)

First, you will need to write the method signature. If you look at the comments there is a good spot to add it. The hasCharacter method is a public static method that returns a boolean value. It needs to take in a character and String as parameters in that order. You can call them what you want, but I called my character x and my string group (ok, maybe not the best names for each…)

Second, you will want to go through the String to see if the character from the parameter exists in the String. You can do this either with a loop and charAt, or you can do it with .contains (group.contains()). I found using the built in String method to be easier.

Step 4: stringShortener(String, String)

Next, you will want to find the comments just above the main method - the ones for the 2 parameter stringShortner method. You will work on this one first, and then go back up to the one parameter version.

This method is your lossy compression! (finally!). The goal is to write a method that takes in a String, and removes all characters that show up in the second string passed in. It will keep a character if it is the start of a word (i.e. following a space)

For example

You can be a good programmer, if you can read this.

would return if VOWELS was used as the list of characters to remove

Y cn b a gd prgrmmr, if y cn rd ths.

Writing stringShortener(String, String)

  • First write the method signature. It is a public static method that returns a String, and takes in two String parameters - a message and a group of characters to remove as a String - in that order.

  • You will then need to create an empty String like was created in the first two methods you wrote. This is the same String you will return. Hint: I would compile here, just to make sure it is compiling.

  • Next, loop through the first String (your message), and check to see if the character at position i is in your group of characters to remove. Hint use hasCharacter! If it is NOT in that group, OR if the character before your current location is a space (the tricky part), then you add it to the the rtn string.

It may be easier to ignore the ‘space’ rule, and get it working. You will then want to try it again, figuring out the space condition. Remember, prototype and repeat tirelessly.

Step 5: stringShortener(String)

Now go up into your code that talks about a stringShortener that only takes in 1 parameter. This is your chance to practice method overloading.

The goal is to assume the default group to remove is VOWELS, as really, who needs vowels when you are writing?

Writing stringShortener(String)

  • First write the method signature. It is the same as the other stringShortener, but only has a String messafe as a parameter

  • call stringShortener(String, String) passing in message and VOWELS as your parameter. Return the value returned from that method!

PROVIDED CODE:

public class LossyString {

// ADD CONSTANT HERE


/**
* Keeps both letters and whitespace only. Everything else is removed
* @param message the string that you want to keep letters and whitespace only
* @return the converted string
*/
public static String lettersAndWhitespaceOnly(String message) {
String rtn = "";

// STUDENT CODE HERE
return rtn;
}


/**
* Removes all whitespace from a string
* @param message the string you wish to have space removed
* @return the new string with whitespace removed
*/
public static String removeWhiteSpace(String message) {
String rtn = "";
// STUDENT CODE HERE

return rtn;
}

/**
* hasCharacter(char, String) Helper method for two-parameter {@link #stringShortener(String, String)}.
* This method determines if one character from the source String is included in the characters
* of the String representing all characters to remove. If so, return true.
*
* @param x A character representing one character from the source String.
* @param group A String representing all characters to remove.
* @return A boolean.
*/
//STUDENT CODE HERE


/**
* stringShortener(String) Remove vowels from a string.
* It will use the default {@link #VOWELS} constant variable for the second parameter, as often
* VOWELS removed from words are easy for our mind to replace.
* @param stringToCheck A String representing the String to check for matching characters in.
* @return A new String with matching characters of source String removed.
*/
//STUDENT CODE HERE

/**
* stringShortener(String, String) Remove all characters listed in one String from another String.
* This method does not ignore case and does not remove a character if it is the
* 'start' of a word after a space.
* i.e.
* <pre>
* You can be a good programmer, if you can read this.
*
* Y cn b a gd prgrmmr, if y cn rd ths.
* </pre>
* @param stringToCheck A String representing the String to check for matching characters.
* @param charsToRemove A String representing the String of characters to remove.
* @return A String with characters removed.
* @see #hasCharacter(char, String)
*/
// STUDENT CODE HERE


public static void main(String[] args) {


}

}

Solutions

Expert Solution

CODE:

public class LossyString
{
   //we define a static final string variable which stores the list of all the vowels
   public static final String Vowels = "aeiouAEIOU";
   //this method only keeps letters and white spaces, removes rest of them
   public static String lettersAndWhitespaceOnly(String message)
   {
       //define a variable "rtn" to store string to be returned
       String rtn = "";
       //this loops traverse through all the characters in the string
       for(int i=0;i<message.length();i++)
       {
           //checks if the i-th characters is in range (a,z) or (A,Z) or whitespace
           //if it is then we add that to return string
           if((message.charAt(i)>='a' && message.charAt(i)<='z') ||
           (message.charAt(i)>='A' && message.charAt(i)<='Z') ||
           message.charAt(i) == ' ')
           {
               rtn+=message.charAt(i);
           }
       }
       //return the "rtn" string
       return rtn;
   }
   //this function takes in a string and returns a string after removing all the whitespaces from it
   public static String removeWhiteSpace(String message)
   {
       //define a variable "rtn" to store string to be returned
       String rtn = "";
       //this loops traverse through all the characters in the string
       for(int i=0;i<message.length();i++)
           //it checks, if element at i-t position is white space or not
           if(message.charAt(i)!= ' ')
               //if not then we add that character to the "rtn" string
               rtn += message.charAt(i);
       //return the "rtn" string
       return rtn;
   }
   //this function takes a character and a string, returns true if character is in string, othrewise false
   public static boolean hasCharacter(char x, String group)
   {
       //we define a boolean variable
       //initialize it with "false", which represents character is not present in the string
       boolean b = false;
       //this loop traverse through all the character in the string to be matched
       for(int i=0;i<group.length();i++)
           //if character is in the string then we make "b" to true, which represents character is in string
           if(x == group.charAt(i))
               b = true;
       //return the boolean value
       return b;
   }
   //this function takes in a string and removes all the vowels from them
   public static String stringShortner(String stringToCheck)
   {
       //define a variable "rtn" to store string to be returned
       String rtn = "";
       //this loops traverse through all the characters in the string
       for(int i=0;i<stringToCheck.length();i++)
           //we call "hasCharacter" function and pass i-th element of string and vowels string
           //if fnction returns false then we add the i-th element to return string else we dont
           if(hasCharacter(stringToCheck.charAt(i), Vowels) == false)
               rtn += stringToCheck.charAt(i);
       //return the "rtn" string
       return rtn;
   }
   //this function takes two string, and removes all the letters of second string from first string
   public static String stringShortner(String stringToCheck, String charsToRemove)
   {
       //define a variable "rtn" to store string to be returned
       String rtn = Character.toString(stringToCheck.charAt(0));
       //this loops traverse through all the characters in the string
       for(int i=1;i<stringToCheck.length();i++)
       {
           //we check for the i-th character with help of "hasCharacter" function, if i-th element is in charsToRemove string
           //if not then we add it to string
           //or we add it if the character is preceded by a white space
           if(hasCharacter(stringToCheck.charAt(i), charsToRemove) == false || stringToCheck.charAt(i-1) == ' ')
               rtn += stringToCheck.charAt(i);          
       }
       //return the "rtn" string
       return rtn;
   }
   public static void main(String[] args)
   {
       //define a string to test letterAndWhitespaceOnly function
       String strs = "!@!(*&(*&)!(!x*@)9191828101";
       //define a string to test rest of the functions
       String strs1 = "You can be a good programmer, if you can read this";
       //tests all the function, one-by-one and print its output
       System.out.println(lettersAndWhitespaceOnly(strs));  
       System.out.println(removeWhiteSpace(strs1));
       System.out.println(stringShortner(strs1));
       System.out.println(stringShortner(strs1, Vowels));
   }
}

OUTPUT:

x
Youcanbeagoodprogrammer,ifyoucanreadthis
Y cn b gd prgrmmr, f y cn rd ths
Y cn b a gd prgrmmr, if y cn rd ths

Ask any questions if you have in comment section below.

Please rate the answer.


Related Solutions

Cinnabar eyes (cn) and reduced bristles (rd) are autosomal recessive characters in Drosophila. A homozygous wild-type...
Cinnabar eyes (cn) and reduced bristles (rd) are autosomal recessive characters in Drosophila. A homozygous wild-type female was crossed to a reduced, cinnabar male, and the F1 males were then crossed to the F1 females to obtain the F2. Of the 400 F2 offspring obtained, 292 were wild type, 9 were cinnabar, 7 were reduced, and 92 were reduced and cinnabar. Briefly explain (2 sentences) these results and estimate the distance between the cn and rd loci.
Bond X Bond Y N (semi-annual) 10 12 Rd (semi-annual) 3.5% 3.5% PMT (semi-annual) 35 35...
Bond X Bond Y N (semi-annual) 10 12 Rd (semi-annual) 3.5% 3.5% PMT (semi-annual) 35 35 PV -1000 -1000 FV 1000 1000 If interests rates rise 1.25% on an annual basis, what will be the change in value of price due to duration for Bond X? and Bond Y?
22.34 Lab 12 B FALL 2019 Python File I/O demo Overview This is a demonstration of...
22.34 Lab 12 B FALL 2019 Python File I/O demo Overview This is a demonstration of File IO Description Read in a list of states from a file, and output those states in alphabetical order. Provided input files A single input file named states.txt is provided that lists the 50 states of the United States - one state per row. Some states have lowercase letters, where some begin with uppercase letters. As a reminder, lowercase letters come after uppercase letters...
HCN dissociates into CN- and protons. A) What is the equilibrium constant at T=298.15 K? B)...
HCN dissociates into CN- and protons. A) What is the equilibrium constant at T=298.15 K? B) At what pH will the reaction move to the left if the solution contains 0.1 M HCN?
If a relation between X and Y is provided by the equation y = 12 +...
If a relation between X and Y is provided by the equation y = 12 + –2.6 x, then we know that there is a _____ relationship between the variables X and Y. A. non-linear B. linear C. constant D. negative E. Only A and C F. Only B and D G. Only B, C, and D
Prove that The OR operation is closed for all x, y ∈ B x + y ∈ B
Boolean AlgebraProve that The OR operation is closed for all x, y ∈ B x + y ∈ BandProve that The And operation is closed for all x, y ∈ B x . y ∈ B
Consider the system x'= -y , y' = -x Sketch the vector field using math-lab. Please...
Consider the system x'= -y , y' = -x Sketch the vector field using math-lab. Please write the code with all the steps. I'm new on math-lab, and I tried to follow some online videos but it did not work right. I have the sketch, but I need the code and the steps to learn it. Thank you,
a) A data is collected from Lab A. Sample mean is 12, SD is 2.4 and...
a) A data is collected from Lab A. Sample mean is 12, SD is 2.4 and sample size if 16. Another set of data from Lab B have a mean of 10 (assuming SDB is also 2.4 and nB=16). If we choose α = 0.05, do you think mean of Lab B is close enough to be considered the “same” as that of Lab A? Why? b) Same as problem 4), except SD of Lab B is SDB=4.4. If we...
2. Numerical “Proof” that for X,Y independent,Var(X+Y) = Var(X−Y) =σ2X+σ2Y: 2.1 As we did in Lab...
2. Numerical “Proof” that for X,Y independent,Var(X+Y) = Var(X−Y) =σ2X+σ2Y: 2.1 As we did in Lab 4, you will need to generate a sample(x,y)-values by independently generating x-values and y-values.(You may choose sample size of 50000.) State the two distributions you will use for generating x-values and y-values,and the corresponding population variances. 2.2 Compute the sample variances of the (X+Y)-values, and of the (X−Y)-values. What value are these two sample variances supposed to estimate? 2.3 Use the formula that explains...
What is the name of the coordination compound     K3[Fe(CN)6]? a. potassium iron (III) hexacyanide b. potassium...
What is the name of the coordination compound     K3[Fe(CN)6]? a. potassium iron (III) hexacyanide b. potassium hexacyanoferrate (II) c. potassium hexacyanoferrate (III) d. ferrous potassium cyanide e. potassium iron cyanide
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT