Strings and GUI Programming Zylabs
Given string userString is "Run!". Indicate char x's value. x = userString.charAt(3);
!
Given string userString is "Run!". Indicate char x's value. x = userString.charAt(4);
(error) The string's last index is 3. Thus, this access is an error, as index 4 doesn't exist for this string.
userText is "March 17, 2034". What does userText.indexOf("April") return?
-1 -1 is not a valid index so is used to indicate that the item was not found. If int x = userText.indexOf("April"), one might then type if (x != -1) { ... } to proceed only if the item was found.
userText is "March 17, 2034". What is the index of the last character in userText?
13 There are 14 characters, and indexing starts with 0, so the index of the last character is 13.
userText is "March 17, 2034". What does userText.length() return?
14 Every character is counted including spaces.
What is the index of the last letter in "Hey"?
2 Indices start at 0, so H is 0, e is 1, and y is 2.
userText is "March 17, 2034". What does userText.substring(userText.length() - 4, userText.length()) return?
2034 That common form can be used to get the last N characters (in this case, the last 4 characters). The length is 14, so the start index is 14 - 4 is 10. The end index is 14 - 1, or 13. Thus, the gotten substring is from index 10 to 13, which are the characters 2034.
What is the length of string "Hey"?
3 The string has 3 characters, so has length of 3.
userText is "March 17, 2034". What character does userText.charAt(userText.length() - 1) return?
4 14 - 1 is 13, so userText.charAt(userText.length() - 1) returns the last character.
userText is "March 17, 2034". What does userText.indexOf(',') return?
8 ',' is the 9th character, so the index is 8.
userString is initially "Done". Indicate userString's value after the statement provided. userString = userString + " now";
Done now The + operator returns a new string that appends a string to another string. A space, n, o, and w are added to the end of "Done".
userString is initially "Done". Indicate userString's value after the statement provided. userString = userString.concat("!");
Done! append() takes "Done" and puts "!" at the end, yielding "Done!". Internally, concat() automatically resizes the string as needed.
userString is initially "Done". Indicate userString's value after the statement provided anotherString = "yet..."; userString = userString + anotherString;
Doneyet... The + operator can take any item that evaluates to a string, like a string literal, or in this case a string variable. That variable's string is "yet...", so y, e, t, period, period, and period get added to "Done".
userString is initially "Done". Indicate userString's value after the statement provided. userString = userString.concat('?');
Error '?' is a character literal due to having single quotes. concat() doesn't work for a character. "?" would work and would yield: Done?
userText is "Monday". userText.charAt(userText.length()) yields 'y'.
False Probably the most common cause of out-of-range access. Use length - 1 (because indexing starts with 0, so last index is length - 1).
userText is "Monday". userText.charAt(7) = '!' may write to another variable's location and cause bizarre program behavior.
False The .charAt() method will generate an exception, usually printing an error and terminating the program.
For string "Light", what is L's index?
L is the first character. A string's first character has index 0.
For string "Light", what is i's index?
L's index is 0, so the next character i has index 1.
userText is "March 17, 2034". What does userText.substring(0, 3) return?
Mar The substring method returns string starting at index 0 and ending at index 2.
For string "You wish!", which character is at index 9?
No such character That string has 9 characters, but the last character ! is at index 8. There is no 9'th character for that string.
Is a string's length the same as a string's last index?
No, the length is 1 greater For example, "Hey" has length 3, but last index 2.
Given string userString is "Run!". Indicate char x's value. x = userString.charAt(0);
R
charAt()
The notation someString.charAt(x) determines the character at index x of a string.
For string "You wish!", which character is at index 4?
W 0:Y, 1:o, 2:u, 3:(space), 4:w.
In the below email username example, what was the second item passed to substring()? public class ExtractUsername { public static void main(String [] args) { Scanner scnr = new Scanner(System.in); String emailText; int atSymbolIndex; String emailUsername; System.out.print("Enter email address: "); emailText = scnr.nextLine(); atSymbolIndex = emailText.indexOf('@'); if (atSymbolIndex == -1) { System.out.println("Address is missing @"); } else { emailUsername = emailText.substring(0, atSymbolIndex); System.out.println("Username: " + emailUsername); } } }
atSymbolIndex The indexOf() method got the index of @. If found (i.e. not -1), then that index was used to indicate the size of the substring preceding the @. So for [email protected], the @ is at index 10, which is the number of letters in AbeLincoln. Thus, substring() starts at index 0 and gets 10 characters, namely "AbeLincoln".
lastIndexOf(item) method
finds the last occurrence of the item in a string, else -1. Example: // userText is "Help me!" userText.lastIndexOf('e') // Returns 6 (last occurrence)
CHALLENGE ACTIVITY 11.1.1: Looking for characters Write an expression to detect that the first character of userInput matches firstLetter. public class CharMatching { public static void main (String [] args) { String userInput = ""; char firstLetter = '-'; userInput = "banana"; firstLetter = 'b'; if (/* Your solution goes here */) { System.out.println("Found match: " + firstLetter); } else { System.out.println("No match: " + firstLetter); } return; } }
firstLetter == userInput.charAt(0)
CHALLENGE ACTIVITY 11.2.1: Combining strings. Retype and correct the code provided to combine two strings separated by a space. secretID.concat(spaceChar); secretID.concat(lastName); import java.util.Scanner; public class CombiningStrings { public static void main (String [] args) { String secretID; String lastName; char spaceChar; secretID = "Barry"; lastName = "Allen"; spaceChar = ' '; /* Your solution goes here */ System.out.println(secretID); } }
secretID = secretID.concat(spaceChar + lastName);
CHALLENGE ACTIVITY 11.4.1: String with digit. Set hasDigit to true if the 3-character passCode contains a digit. import java.util.Scanner; public class CheckingPasscodes { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); boolean hasDigit; String passCode; hasDigit = false; passCode = scnr.next(); /* Your solution goes here */ if (hasDigit) { System.out.println("Has a digit."); } else { System.out.println("Has no digit."); } } }
for (int i = 0; i < passCode.length(); i++){ if (Character.isDigit(passCode.charAt(i))){ hasDigit = true; break; } } Long handed: if (Character.isDigit(passCode.charAt(0))){ hasDigit = true; } else if (Character.isDigit(passCode.charAt(1))){ hasDigit = true; } else if (Character.isDigit(passCode.charAt(2))){ hasDigit = true; }
CHALLENGE ACTIVITY 11.4.2: Whitespace replace. Write code to print the location of any space in the 2-character string passCode. Each space detected should print a separate statement followed by a newline. Sample output for the given program: Space at 1 import java.util.Scanner; public class FindSpaces { public static void main (String [] args) { String passCode; passCode = "A "; /* Your solution goes here */ } }
for (int i = 0; i < passCode.length(); i++){ if(Character.isWhitespace(passCode.charAt(i)){ System.out.println("Space at " + i); } }
charAt(index) method
generates an exception if the index is out of range for the string's size. An exception is a detected runtime error that commonly prints an error message and terminates the program.
indexOf(item) method
gets index of first item occurrence in a string, else -1. Item may be char, String variable, or string literal. Example: // userText is "Help me!" userText.indexOf('p') // Returns 3 userText.indexOf('e') // Returns 1 (first occurrence) userText.indexOf('z') // Returns -1 userText.indexOf("me") // Returns 5
CHALLENGE ACTIVITY 11.3.2: Print two strings in alphabetical order. Print the two strings in alphabetical order. Assume the strings are lowercase. End with newline. Sample output: capes rabbits import java.util.Scanner; public class OrderStrings { public static void main (String [] args) { String firstString; String secondString; firstString = "rabbits"; secondString = "capes"; /* Your solution goes here */ } }
if (firstString.compareTo(secondString) < 0){ System.out.println(firstString + " " + secondString); } else{ System.out.println(secondString + " " + firstString); }
CHALLENGE ACTIVITY 11.2.3: Using indexOf(). Print "Censored" if userInput contains the word "darn", else print userInput. End with newline. Note: These activities may test code with different test values. This activity will perform three tests, with userInput of "That darn cat.", then with "Dang, that was scary!", then with "I'm darning your socks.". See "How to Use zyBooks". . Also note: If the submitted code has an out-of-range access, the system will stop running the code after a few seconds, and report "Program end never reached." The system doesn't print the test case that caused the reported message.
if (userInput.indexOf("darn") > 0){ System.out.println("Censored"); } else{ System.out.println(userInput); }
CHALLENGE ACTIVITY 11.3.1: String comparison: Detect word. Write an if-else statement that prints "Goodbye" if userString is "Quit", else prints "Hello". End with newline. import java.util.Scanner; public class DetectWord { public static void main (String [] args) { String userString; userString = "Quit"; /* Your solution goes here */ } }
if(userString.equalsIgnoreCase("Quit")){ System.out.println("Goodbye"); } else{ System.out.println("Hello"); }
String
is a sequence of characters in memory. Each string character has a position number called an index, starting with 0 (not 1)
substring(startIndex, endIndex) method
returns substring starting at startIndex and ending at endIndex - 1. The length of the substring is given by endIndex - startIndex. Example: // userText is "http://google.com" userText.substring(0, 7) // Returns "http://" userText.substring(13, 17) // Returns ".com" // Returns last 4: ".com" userText.substring(userText.length() - 4, userText.length())
CHALLENGE ACTIVITY 11.2.2: Name song. Modify songVerse to play "The Name Game" (OxfordDictionaries.com), by replacing "(Name)" with userName but without the first letter. Ex: If userName = "Katie" and songVerse = "Banana-fana fo-f(Name)!", the program prints: Banana-fana fo-fatie! Ex: If userName = "Katie" and songVerse = "Fee fi mo-m(Name)", the program prints: Fee fi mo-matie Note: You may assume songVerse will always contain the substring "(Name)". import java.util.Scanner; public class NameSong { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String userName; String songVerse; userName = scnr.nextLine(); userName = userName.substring(1); // Remove first character songVerse = scnr.nextLine(); // Modify songVerse to replace (Name) with userName without first character /* Your solution goes here */ System.out.println(songVerse); } }
songVerse = songVerse.replace("(Name)", userName);
indexOf(item, indx) method
starts at index indx. Example: // userText is "Help me!" userText.indexOf('e', 2) // Returns 6 (starts at index 2)