Introduction
Last lab, we worked with methods to perform some arithmetic calculations related to salaries. Today, we will continue practicing using methods in our programs, while learning more about the string variable type.
About Chars
Chars are a primitive variable type. They store single characters, which actually correspond to ASCII values, or numerical values. They are initialized with the character in single quotes. For example:
char letter = 'a';
Because chars correspond to ASCII values, they work well with the integer variable type. If you wanted to find the numerical value of a char, you could cast it to an int and print it, like this:
char letter = 'a';
System.out.println((int)letter);
This would print 97.
You can also assign chars to int variables without casting, like so:
char letter = 'a';
int number = letter;
The variable number would now hold the value of 97.
You can also perform actions on a char, similar to methods with strings, but you must use the Character wrapper class. Check out the Character wrapper class Java Doc for more information.
About Strings
Strings are an object variable type. They are immutable, which means they can not be changed. That doesn’t mean you can never modify a string when writing a program, it just means that when you’re modifying it, it’s actually creating a new string each time a change is made.
Strings are stored as arrays of chars behind the scenes. You don’t have to worry about that too much right now, but it does help to understand that strings are also indexed. Their indexing is 0-based, so the first character of the string is at index 0.
If a string is used without being stored in a variable, such as in a print statement, it is referred to as a literal.
Because strings are objects made from the String class, they also have some handy associated methods. Some of the most commonly used string methods for this class will be:
-
charAt(int index) returns character at a specific index
-
length() returns length of string
-
equals(Object ob) used to compare strings to see if they’re equivalent. Don’t use == ! This returns a boolean.
-
compareTo(Object ob) used to compare strings (or objects!) lexicographically. If strings are equal, method returns 0.
Refer to the Java Docs for strings for a complete list of methods.
Strings can also be concatenated, which means they are combined into one string. For example, concatenating “Good” and “ morning” would result in a single string, “Good morning”.
Declaring and initializing a string is similar to any other data type. The initialization must be in double quotes. For example:
String greeting = "Hello!";
To call one of the methods above, just follow the string with a period and the method name. For example:
greeting.length();
Using String Format
In this zybooks section, you learned about using System.out.printf() to format Strings. You can also use the method String.format() in a similar way to strucutre a string. Here is an outside resource with more examples.
String.format() takes at least two parameters and returns a string, like this:
String returnedString = String.format("format string, which includes specifiers", specifier arguments);
The specifiers in the format string let the compiler know where to substitute the arguments found after the format string. They are denoted by a % symbol, a specific letter to indicate the variable type, and other sub-specifiers.
For example:
String dinosaur = "ankylosaurus";
String period = "Cretaceous";
int time = 68;
String dinoInfo = String.format("I am an %s, from the %s period, which was over %d million years ago", dinosaur, period, time);
This would output:
I am an ankylosaurus, from the Cretaceous period, which was over 68 million years ago.
###Testing Your Code For today’s lab, we will be giving you a method called runTests() that will test your code. Initially, it will be commented out, and as you complete each method, uncomment the associated testing in the runTests() method and run your program. Feel free to add more test cases to this method, as it will not be graded.
Step 1 : concatenateStrings
Reviewing Method Signatures
Last lab, we worked with methods. We will review method signatures and their structure now.
Remember the format of the method signature, including access modifiers, return types, parameters, and method names.
Write a method signature for a method that takes in two strings and concatenates them into one string, with a space between the two characters. This method should be visible by anyone, and should require an instantiated object to be called. The concatenated string should be returned, and the method should be named concatenateStrings(); You have already worked with string concatenation, but if you’re stumped, review the example in the introduction.
Now, fill in the method body for your method.
Testing Your Method
Uncomment the section in the runTests() method labeled concatenateStrings(). Run your program, and check the output.
Step 2 : charToASCII(char c)
Write a method that returns the ASCII value of a character. Review the About Chars section above if you get stuck. This might seem like unnecessary code, as you should find that the method can be completed in a single line. However, it’s important to remember how chars can be easily converted to an integer value.
The method signature will not be given to you, but this method should:
- be visible to anyone
- require an instance of the class to be called
- return an int
- have one parameter - a char
- be named charToASCII
Testing Your Method
Uncomment the section in the runTests() method labeled charToASCII(). Run your program, and check the output.
Step 3 : getLastChar(String str)
Write a method that returns the last character of a word that is passed as a parameter. The character returned should always be uppercase, no matter the case of the character in the string.
Hint 1: Review the Character wrapper class and the Java Doc referenced in the introduction of this lab.
Hint 2: What is the index of the last character of the string? If you don’t know, what method could you use to figure it out?
The method signature should be as follows:
public char getLastChar(String str){ }
Testing Your Method
Uncomment the section in the runTests() method labeled getLastChar(). Run your program, and check the output.
Step 4 : translateWord(String str)
Write a method that translates any string with four characters, (a word, a four digit number, a collection of random characters), into its ASCII code equivalent, with spaces in between. Build upon what you used in the previous methods in this lab, using chars, string concatenation, and the string method charAt().
For example, if you gave “yams” to the method, it should return 121 97 109 115, because each number corresponds to a character’s ASCII value.
What happens if you remove spaces in between? Try it, and see what happens. Modify your method so it returns the string without any spaces.
It should have the following method signature:
public String translateWord(String str){ }
Testing Your Method
Uncomment the section in the runTests() method labeled translateWord(). Run your program, and check the output.
Step 5 : madLib(String noun1, double number, String pastTenseVerb, String adjective, String noun2)
Write a method that simulates the Mad Libs you may or may not have done as a child. Check out this link if you’re not familiar with them. The idea is to be given a sentence or short paragraph with placeholders for specific types of words that can be substituted in to create an entertaining story.
This method will take in five parameters and use String.format() to return a string with two sentences and the parameter values substituted in. The parameters should be substituted in the order they appear in the method signature, which is as follows:
public String madLib(String noun1, double number, String pastTenseVerb, String adjective, String noun2){};
The words and number should be substituted in the following sentence:
Today I went to the store and bought a (noun) for $(number). Then I (verb) and saw a (adjective) (noun2).
Important: The number should only include two decimal places, and the two sentences should be split onto two lines.
Testing Your Method
Uncomment the section in the runTests() method labeled madLib(). Run your program, and check the output.