Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Activity: Using Classes and Objects Page 1 of 11 Terminology: new operator class object reference variable instantiation dot (.) operator parameter return alias garbage collection

image text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribed

Activity: Using Classes and Objects Page 1 of 11 Terminology: new operator class object reference variable instantiation dot (.) operator parameter return alias garbage collection String class immutable Java API package import declaration Random class Math class NumberFormat class DecimalFormat class wrapper class autoboxing unboxing method static method constructor Course Coding Standard Additions When using the import declaration, import classes from the same package individually (i.e. do not use the * notation). For example, you should have import java.util.Scanner and import java.util. Random rather than having import java.util.* which imports everything in the java.util package. When making calculations with T, use Math.PI rather than the literal value such as 3.141. You should always use constants when they are available. From now on, when using a Scanner object to scan input (e.g., from the keyboard), use nextLine to get numerical input from the user and convert it to a number using methods from the corresponding wrapper class. For example to read in an int value from Scanner userInput: int myInt = Integer.parseInt (userInput.nextLine()); For example to read in a double value from Scanner scan: double myDouble = Double. parseDouble (user Input.nextLine()); Page 1 of 11 Activity: Using Classes and Objects Page 2 of 11 Goals: By the end of this activity you should be able to do the following: Understand how to instantiate an object using the new operator Use the Java standard library (the Java API) to look up a class Use the String class and the Scanner class Construct a viewer canvas and run your program in the canvas Program Description: You will create a program that exchanges letters in a String to encode a message. In-lab Directions: As you build your program incrementally by entering each of the code segments below, you should compile and run your program after each segment is completed. This will allow you to verify that your program is correct after each step as you progress toward the completed program. MessageConverter.java This program will read in a message from the user and then require the user to enter a number. The following will happen based on the number entered by user: If the user enters a 1, the message will be printed trimmed. o If the user enters a 2, the message will be printed in lower case. o If the user enters a 3, the message will be printed in upper case. o If the user enters a 4, the message will be printed with all vowels replaced with underscores. . If the user enters a 5, the message will be printed without the first and last character. o Any other number should generate an appropriate message. Create a class called MessageConverter that includes a main method. Also add an import statement for the java.util.Scanner class. The import statement should be the first line in your Java file (i.e., it comes before the class declaration as well as comments) In the main method, declare the following variables: - user Input: Scanner object for reading the user input from the keyboard. Scanner userInput = new Scanner (System.in); message: String object for the user input; initialized to an empty String String message = ""; output Type: An int representing the type of output the user wants result: String object for the converted message; initialized to an empty String. String result = ""; Request input from the user then get user input using the nextLine() method of the Scanner class. System.out.print("Type in a message and press enter: \t> "); message = user Input.nextLine(); Page 2 of 11 Activity: Using Classes and Objects Page 3 of 11 Now get the user's input for the output type. Make sure that you understand how the code below works. Notice that this is a call to the print method rather than println. System.out.print(" Output types :" + " \to: As is". + " \tl: Trimmed" + " \t2: lower case" + " \t3: UPPER CASE" + " \t4: vw_ls rpl_c_d" + " \t5: Without first and last character" + " Enter your choice: "); outputType = Integer.parseInt (user Input.nextLine()); Get user input as a String Use the static parseInt method of the Integer class to convert the string to an int value. Set up an if statement that will print out the appropriate message based on the user's selected output type. Note that you can write code for alternate conditions in the if statement using else if after the if block. if (outputType == 0) { // as is else if (outputType == 1) { // trimmed else if (outputType == 2) { // lower case else if (output Type == 3) { // upper case else if (outputType == 4) { // replace vowels else if (outputType == 5) { // without first and last character else { // invalid input After the entire if-else statement, add the following line of code to print out the result. System.out.println(" " + result); Compile now and after each step below as you fill in the if-else-if-else in the following steps. The first condition for outputType equal to 0 sets the result to the original message which may include leading and/or trailing spaces. if (output Type == 0) { // as is result = message; Page 3 of 11 Activity: Using Classes and Objects Page 4 of 11 Because message references an instance of the String class, we can use the methods in the String class to return a new String that is a modified version of the original String referenced by message (the original String object is not changed). To see the available methods in the String class, go to the Java API at http://docs.oracle.com/javase/8/docs/api/ and find the String class in the lower left pane on the page and left-click on it. This will open the String page in large right window of the API as shown below. You should become familiar with the API since it describes all of the classes that come with the JDK. String lava ) + decoracle.com /docs/ inch Most visited at Headlines Google G GRASP - Google 1210 We-CAT Une Tree Dee P ing A M Index Help D- ALO s Standard Ed. 7 Overview Package Cans Prav Classes Class Summary Need Field Cor Frames No Frames DeatFeld I Cant Method d Packages walang String Class Class String j ong Sering All implemented interfaces: Seriable Cha m ber String Butt Stream public final class string extends Object implements Serialible, comparable, CharSequence The string classes cha remedies of the n sons, such as "abe In the main window on the right side, click method at the top or scroll down to Method Summary to see the methods that our String object message can use. String methods do not modify the String object upon which they are called. Instead, if a method has a String return type, then it returns a new String object which may be a modified version of the original String. string One Pulom ) + e dos oracle.com /api Most Vine Latest Headlines Google G GRASP e- 1230 Web-CATESSE Engr Map L KC >> Method Summary Methods Modifier and Type char The list of String methods includes the return type and a description of each method. For example, the charAt method returns a char value at the specified index. Method and Description charat (int index) Reums the char view the specified index codePointAt(int index) Returns the character Unicode de especified index coderointBefore(int index) Returns the che Unicode code po ben the specified emre coderoint count(int begin index, Stupur Returns the number of Unicode code points in the speciales range of this string compacto (String anotherstring) Compares two strings lexicographical compare toIgnorecase string str) Page 4 of 11 Activity: Using Classes and Objects Page 5 of 11 The second condition for output Type equal to 1 sets the result to the trimmed value of the message; i.e., we can use the trim method removes any leading or trailing whitespace. The API entry for a method shows the return type for the method in the left and the method name with formal parameters, if any, on the right along with a brief description of what the method does. So the entry shown below for the trim method indicates that it returns a String and takes no parameters. Remember, the trim method does not modify the String object upon which it is called. Instead it returns a new String object which is the trimmed version of original String Returns a String Method name - there are no formal parameters for this method String trim() Returns a string whose value is this string, with any leading and trailing whitespace removed. Be sure to compile each time you complete a part of the if-else-if-else below else if (output Type == 1) { // trimmed result = message.trim(); The third condition for output Type equal to 2 sets the result to the lower case value of the message; i.e., we can use the toLowerCase method. The Java API entry shown below for the to LowerCase method indicates that it returns a String and takes no parameters. Returns a String Method name - there are no formal parameters for this method String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale. Based on this knowledge, you can now invoke the toLowerCase method on our message object to return its value in lower case. Place the following code in second block of the if statement: else if (outputType == 2) { // lower case result = message.toLowerCase(); Look at the API description for the toUpperCase method and place the following line in the second block of the if statement: else if (outputType == 3) { // upper case result = message.toUpperCase(); Now write code that will replace specified characters in the message with other characters. In order to change a character, we need to use the replace method of String to change certain characters of our string. Take a look at the replace method in the Java API. We see that it returns a String and that it requires two parameters: the character you want to replace and the new character. Note there are two versions of replace: the first takes parameters of type char Page 5 of 11 Activity: Using Classes and Objects Page 6 of 11 (e.g., 'a' or 'e').and the second takes parameters of type CharSequence which includes String literals (e.g., "a" or "abc"). In the code below, we will use the char version. Returns a String String Method name and two formal parameters replace(char oldChar, char newChar) Returns a string resulting from replacing all occurrences of oldChar in this string with newChar. String replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. As with the other String methods, the replace method does not modify the String object it. Instead it returns a new String object in which the new character has replaced the old character. First, use the replace method to change all of the a's to underscores. The following line of code replaces the 'a' characters of the message value and then assigns the new version of message to result. Again, note that message itself remains unchanged. else if (outputType == 4) { // replace vowels result = message.replace('a', '_'); Now complete the translation by converting the remaining vowels to underscores for outputType equal to 4. else if (outputType == 4) { // replace vowels result = message.replace('a', '_'); result = result.replace('e', '_'); result = result.replace('i'; '); result = result.replace('o', result = result.replace('u', 2 ); Now use the substring method and length method to extract a part (or substring) of the message. Returns a String Method name and formal parameters String substring(int beginIndex) Returns a string that is a substring of this string. String substring(int beginIndex, int endIndex) Returns a string that is a substring of this string. Recall the characters in a String are indexed beginning at 0. Since the requirement here is for result to include everything except the first and last character, use the second version of Page 6 of 11 Activity: Using Classes and Objects Page 7 of 11 substring with 1 as the parameter beginIndex and message.length() - 1 as endIndex. else if (output Type == 5) { // without first and last character result - message.substring(1, message.length() - 1); Finally, if the user enters a number other than 1, 2, 3, 4, or 5, result should be set to an error message. else { // invalid input) result = "Error: Invalid choice input."; Test your program under each of the conditions. This is for the ice, entero. Original ("as is"): For the message, enter: This is a test." Be sure to include the five leading spaces, but omit the quotes. For choice, enter 0. Type in a message and press enter: > This is a test. Output types: 0: As is 1: Trimmed 2: lower case 3: UPPER CASE 4: v_w_ls r_pl_c_d 5: Without first and last character Enter your choice: 0 This is a test. Trimmed: Use the Up arrow key to retrieve the message you entered above, then for choice, enter 1. Notice the five leading spaces have been removed in the output. Type in a message and press enter: This is a test. Output types: 0: As is 1: Trimmed 2: lower case 3: UPPER CASE 4: v_w_ls r_pl_c_d 5: Without first and last character Enter your choice: 1 This is a test. Page 7 of 11 Activity: Using Classes and Objects Page 8 of 11 Lower case: Use the Up arrow key to retrieve the message you entered above, then for choice, enter 2. Notice the output is in all lower case but the five leading spaces have not been removed. Type in a message and press enter: This is a test. Output types: 0: As is 1: Trimmed 2: lower case 3: UPPER CASE 4: v_w_ls r_pl_c_d 5: Without first and last character Enter your choice: 2 this is a test. Upper case: Use the Up arrow key to retrieve the message you entered above, then for choice, enter 3. Notice the output is in all upper case but the five leading spaces have not been removed. Type in a message and press enter: > This is a test. Output types: 0: As is 1: Trimmed 2: lower case 3: UPPER CASE 4: v_w_ls r_pl_c_d 5: Without first and last character Enter your choice: 3 THIS IS A TEST. Vowels replaced: Use the Up arrow key to retrieve the message you entered above, then for choice, enter 4. Notice the output has the vowels removed but the five leading spaces have not been removed. Type in a message and press enter: This is a test. Output types: 0: As is 1: Trimmed 2: lower case 3: UPPER CASE 4: v_w_ls r_pl_c_d Page 8 of 11 Activity: Using Classes and Objects Page 9 of 11 5: Without first and last character Enter your choice: 4 Th_s _s _ t_st. Without first and last character: For the message, enter This is a test." This time do not enter any leading or trailing spaces. Then for choice, enter 5. Notice the output has the first and last character removed. Type in a message and press enter: > This is a test. Output types: 0: As is 1: Trimmed 2: lower case 3: UPPER CASE 4: v_w_ls r_pl_c_d 5: Without first and last character Enter your choice: 5 his is a test Invalid input: Type in a message and press enter: > This is a test. Output types: 0: As is 1: Trimmed 2: lower case 3: UPPER CASE 4: v_w_ls r_pl_c_d 5: Without first and last character Enter your choice: 7 Error: Invalid choice input. Try the input "A message" for the message and choose to replace all vowels with underscores. What do you notice about the output? Why do you think that one of the vowels was not replaced? How would you go about correcting the issue? You don't have to make this change -- just think about it. Web-CAT - After you have completed the program in this activity, you should submit your Message Converter.java file to Web-CAT. This is the only file you will submit for this activity. Page 9 of 11 Activity: Using Classes and Objects Page 10 of 11 Using the Viewer Canvas with your MessageConverter program Now we want to create a viewer canvas so we can see what is happening in the MessageConverter program step-by-step as it runs. Note that we could have done this step as soon as the variables had been declared above. For your project assignments, you should consider creating a canvas at any point that you need insight into exactly what is happening in your program. With Message Converter.java in the CSD edit window, click the Run in Canvas button on the toolbar. In the CSD window, you should see that the program is stopped at the first executable statement, and you should see an empty viewer canvas window as shown below. MessageConverter jgrasp canvas.xml courses comp121012013-08-Fall Web\Lab Activities... Eile Edit View Run Debug Help O Delay D 0.07 sec It co > > + I Click debug step or step-in button until you see objects and/or primitives of interest in the debug variables pane. Drag objects and primitives from the debug variables pane and elsewhere onto this canvas Status: running user program in canvas As indicated by the message in the canvas, click the debug step button to execute the statement to create a Scanner object on System.in which is the keyboard. You should now see the variable name userInput in the Debug tab. Now click the step button three more times so that you see message, result, and output Type in the Debug tab. Now drag each of these variables into the canvas window and arrange them as shown in the figure below. Click the Save button on the canvas toolbar. MessageConverter jgrasp canvas.xml D courses comp12102013-08-Fall Web\Lat\Activities. O X File Edit View Run Debug Help Og Delay 0 0.07 sec > > > I userinput - 10 10 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 message result output Type | 0 GO Status: running user program in canvas Page 10 of 11 Activity: Using Classes and Objects Page 11 of 11 Now click the play button , and your program will begin auto-stepping until is pauses waiting for input. After you enter the requested input each time, the viewers on canvas will be updated. The run in canvas will continue until your program terminates at which time the viewers on the canvas will display their last values as shown in the example below for message "This is a test and outputType = 4. O X MessageConverter.jgrasp canvas.xml D:\courses comp1210 2013-08-Fall Web Lab Activities. Eile Edit View Run Debug Help af Delay = 0.50 sec 1 > > userinput Er 14 in 15 4 16 In 18 10 19 10 20 10 21 10 22 10 23 17 2 output Type This is a test result Th__s_t_st Status: run in canvas ended Although we created the canvas for the MessageConverter after the program was completed, it would have been even more appropriate to create the canvas as the program was being coded, especially if you were encountering logical errors in your program. For example, if you sense that an error has occurred at particular place in the program, you should set a breakpoint on the statement where you want to examine the behavior. [To set a breakpoint, move the mouse over the margin to the left of the statement until you see the red octagon (stop sign symbol) and then left-click the mouse.] Then instead of clicking the Run in Canvas button on the toolbar, click the Debug button . The program will run to the breakpoint and stop. You can single-step (or perhaps step-in ) and observe the variables in the canvas and debug tab to help determine the nature of the error so that you can correct Page 11 of 11

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Systems Analysis And Synthesis Bridging Computer Science And Information Technology

Authors: Barry Dwyer

1st Edition

0128054492, 9780128054499

Students also viewed these Databases questions

Question

Eliminate street slang.

Answered: 1 week ago