Lab 2: Java String objects and methods — CS 112, Boston University CS 112 Fall 2021 Home Syllabus Schedule Lectures Labs Problem Sets Staff Office Hours Resources Collaboration Policies Blackboard Piazza Gradescope Lab 2: Java String objects and methods Piazza Pointers Task 1.0: Java Strings Task 1.1: String objects and their methods Task 1.2: Strings and their methods (continued) Task 2: Strings and User Input Extra Practice! Using folders We strongly encourage you to create a separate folder for each lab and each problem set, so that you can more easily keep track of your work. For example, you could create a folder called lab2 for your work on this lab, and put all of the files for this lab in that folder. Piazza Pointers You can — and should! — search for related questions before you post a new question. You can post anonymously, so that other students won’t see your name. If you need to show us part of your work in order to ask your question, you can make a private post that only the course staff can see. However, if your question that doesn’t reveal your work, please don’t post it privately, because then other students can’t benefit from it. Non-private questions are also more likely to get a quick reply, because more people can see and answer them. Task 1.0: Java Strings Task 1.1: String objects and their methods In the next problem set, there will be several problems in which you will need to work with String objects in Java. With Java, most operations involving strings – including indexing and slicing – are done using methods that are called on the string object. This is an example of a code trace using Java Strings. The table below compares the ways in which some common string operations would be accomplished in Python and Java: operation in Python in Java assigning to a variable (and, in Java, declaring the variable) s1 = 'Boston' s2 = "University" String s1 = "Boston"; String s2 = "University"; concatenation s1 + s2 s1 + s2 finding the number of characters len(s1) s1.length() indexing (note: Java does not have negative indices) s1[0] s2[-1] s1.charAt(0) s2.charAt(s2.length()-1) (see the notes below the table for a key fact about this method) slicing s1[1:4] s2[3: ] s1[ :5] s1.substring(1, 4) s2.substring(3) s1.substring(0, 5) converting all letters to uppercase s1.upper() s1.toUpperCase() converting all letters to lowercase s2.lower() s2.toLowerCase() determining if a substring is in a string s2 in s1 'sit' in s2 s1.contains(s2) s2.contains("sit") finding the index of the first occurence of a character or substring s1.find("o") s2.find('ver') s1.indexOf('o') s2.indexOf("ver") testing if two strings are equivalent s1 == s2 s1 == 'Boston' s1.equals(s2) s1.equals("Boston") Additional notes: Java has a separate type called char for values that consist of a single character. Literals of this type are surrounded by single quotes (e.g., the 'o' in the call s1.indexOf('o')), whereas string literals must be surrounded by double quotes. The charAt() method that we use for indexing in Java returns a value of type char. For example, the call s1.charAt(0) in the table above would return the char value 'B', since 'B' is the first character in the string "Boston". Task 1.2: Strings and their methods (continued) Given the information above, here are the tasks you should perform: To ensure that you understand how the above string operations work in Java, write a simple Java test program which you can use to play around with the different string operations. Begin by initializing two string variables in your main method (which can be used in the later tasks). Example: String s1 = "Boston";
String s2 = "University";
Test that these variables still have their values, the statements: System.out.println(s1);
System.out.println(s2);
should output: Boston
University
If for some reason the variables don’t have these values, redeclare the variables We’re now going to solve a series of puzzles in which we construct an expression involving operations on s1 and/or s2 to produce a specified target value. For example, let’s say that we want to construct an expression involving s1 or s2 that produces the following value: "ton"
One possible expression that works for this puzzle is s1.substring(3, 6). System.out.println( s1.substring(3, 6) );
should output: ton
Now solve the puzzles below by writing in your main function for each problem in your StringTest.java file. Construct an expression involving s1 or s2 that produces the following value: "Uni"
Construct an expression involving s1 or s2 that produces the following value: "UNI"
Hint: Chain two method calls together. For example: System.out.println( s1.toLowerCase().substring(0, 3) );
should output: bos
Construct an expression involving s1 or s2 that produces the following value: 'v'
Note that the single quotes mean that you must produce a char, not a String. See the notes under the table above that discuss the char type. Construct an expression involving s1 or s2 that produces the following value: "STONE"
Write a static method called replaceStart that takes two strings s1 and s2, and does the following: If the length of s1 (call it s1Len) is less than the length of s2, the method returns a string in which the first s1Len characters of s2 are replaced by s1. For example: System.out.println( replaceStart("abc", "xxxxxxx") );
should output: abcxxxx
and, System.out.println( replaceStart("hello", "xxxxxxx") );
should output: helloxx
If the length of s1 is greater than or equal to the length of s2, the method just returns s1. For example: System.out.println( replaceStart("hello", "bye") );
should output: hello
Why does the method replaceStart need to be called from within the println method? In other words, what would you expect to happen if our program just made the call to replaceStart on its own line, rather than calling it as part of a println? Make sure you understand. Task 2: Strings and User Input Download the following file (in your lab2 directory) on your computer. StringTest.java This program shows an example of the use of the hasNextMethod of the Scanner class which allows for continuous user input. Open it up in your IDE, run the program and understand how it works. It may help to look up the methods of the Scanner class (simple google search will suffice) and review the method hasNextLine. Change the method inputString to accept a string argument and to return the number of times that the string argument was input by the user. A possible call in the main method could be: num_times = inputString( "CS112" );
The inputString method will work as before, but it should now keep track of the number of times that the user input the passed string, and return that value to the main method. The main method should be changed to correctly output how many times that the passed input string was entered (i.e. the value returned by the method inputString). One possible sample run is as follows: Welcome to the String Test Program!
You are looking for the string CS112.
Type in a line of text (a String) or "quit" to end: Hello
You input: Hello
Type in a line of text (a String) or "quit" to end: CS112
You input: CS112
Type in a line of text (a String) or "quit" to end: CS112
You input: CS112
Type in a line of text (a String) or "quit" to end: quit
You entered the string CS112 two times!
bye
Run the program again, but this time, only input the desired string once. Is your program output gramatically correct? What if the desired input string is not entered? How can you ensure the output is gramatically correct regardless of the number of times the input string was entered? Extra Practice! If you get through the exercises above, congratulations! For extra practice, you can try some exercises from an excellent site called Practice-It. Go to Practice-It. Create an account. Select the group of problems entitled Building Java Programs, 3rd edition. Select BJP3 Chapter 3: Parameters and Objects. Try any of the following: BJP3 Self-Check 3.18-3.21 BJP3 Exercise 3.17–3.22 The system will test your solution and tell you whether it is correct. Last modified on September 17, 2021.