Computer Science 252
Problem Solving with Java
Spring 2016, The College of Saint Rose
This is the third of the three "review" labs that are designed to refresh and sharpen your prerequisite Java programming skills. Again, there are a few programs to write, but all are things you should be comfortable doing, maybe with a little refreshing of your memory, having completed the prerequisites successfully.
You are to work individually on these tasks. Searching for similar programs on the Internet (or anywhere) is not permitted, and would be counterproductive to your ability to learn how to approach these straightforward tasks. However, you should feel free to ask your instructor, our graduate assistant, or the ASC tutors for help as you work through them.
This third review lab focuses on text/string processing. All programs for this lab are once again Java applications.
Getting Set Up
To get your BlueJ environment set up for this week's lab assignment, start BlueJ and choose "New Project" from the "Project" menu. Navigate to your folder for this course and choose the name "Lab4" (no spaces) for the project.
Java String Overview
Before we get to practice programs, let's review (or introduce, in some cases) Java's String class.
Java API Documentation: java.lang.String
Java's String class is used to represent sequences of characters. The same term is used in most modern programming languages. String provides many frequently-used methods, some of which you will practice with in this lab.
You have hopefully used Java Strings in many situations:
msg.setText("Got me!");
System.out.println("You clicked " + count + " times.");
Java's String class is also unique in the sense that it does not fall clearly into one of the two categories of types in Java:
Java considers String to be an object type. But Strings share features with both object and non-object types.
Some useful String methods
String courseName = "Data Structures"; int nameLength = courseName.length();
nameLength gets the value 15.
courseName.indexOf("S")
returns the value 5. Note that indexing starts at 0, as it does with arrays.
Of course, we can also say
String searchString = "S";
and then
courseName.indexOf(searchString)
Another option is:
public int indexOf(String s, int startIndex)
which begins its search at the specified index.
What are the results of each of the following?
courseName.indexOf("Struct", 2) courseName.indexOf("Struct", 8) courseName.indexOf("t", 2) courseName.indexOf("t", 6) courseName.indexOf("t", 7)
Answers: 5, -1, 2, 6, 10.
Here is a method that searches for the number of occurrences of a String, word, in another String, text.
public int wordCount(String text, String word) { int count = 0; int pos = text.indexOf(word,0); while (pos >= 0) { count++; pos = text.indexOf(word,pos+word.length()); } return count; }
What does the above method return for these call?
wordCount("yabbadabbadoo","abba"); wordCount("scoobydoobydoo","oo");
How about this one? [Side note: I bet everyone knows where the strings above come from but what about this next one?]
wordCount("bubbabobobbrain","bob");
Is that what you want? Think about how would you modify the method to include the overlapped "bob"s above.
Note that "s" and "S" are different strings.
public String toLowerCase() public String toUpperCase()
A case-insensitive word counter/finder differs from the above code only by the added two lines in the following.
private int substringCounter( String text, String word) { int count = 0; int pos; text = text.toLowerCase(); word = word.toLowerCase(); pos = text.indexOf(word,0); while ( pos >= 0 ) { count++; pos = text.indexOf(word,pos+word.length()); } return count; }
Note that the assignment statements to text and word are required. String methods do not manipulate the given String. They make a brand new one. We say that Java Strings are immutable.
public String substring(int startIndex, int indexBeyond)
For example:
String countText = "3 Balls, 2 Strikes, 2 Outs"; String strikesOnly; strikesOnly = countText.substring(9,18);
Note that if we omit the second parameter, the substring returned is the one starting at startIndex and will include the rest of the string.
Continuing the example above:
String outsOnly; outsOnly = countText.substring(20);
Miscellaneous String methods
public boolean startsWith(String s) // true only if this string starts with s public boolean endsWith(String s) // true only if this string ends with s public boolean equals(String s) // true only if this string has same sequence of chars as s public boolean equalsIgnoreCase(String s) // true only if this string has same sequence of chars as s // except capital & lower case letters considered the same public int lastIndexOf(String s) public int lastIndexOf(String s, int startIndex) // return index of last occurrence of s (occurring at or // before startIndex) in this string, and -1 if no match. public String replace(char oldChar, char newChar) // Returns a new string resulting from replacing all // occurrences of oldChar in this string with newChar. public String trim() // Returns a new string with leading and trailing spaces removed. public int compareTo(String s) // Returns negative int if string before s in case-sensitive // dictionary order; // returns 0 if equal // returns positive int if string after s in case-sensitive // dictionary order. public char charAt(int index) // Returns the character at the specified index.
Converting Strings to numeric types
Before we move to the String practice programs, we consider the conversion of String data to numeric types.
We have seen already that a Scanner can retrive numeric data from its input with the nextInt and nextDouble methods. This leads to one technique for converting String data to numbers. Just as we can use the keyboard or the contents of a file as the input for a Scanner, we can also use a String:
Scanner nums = new Scanner("17 23.2"); int first = nums.nextInt(); double second = nums.nextDouble();
This will result in the number 17 in the variable first, and 23.2 in the variable second.
Alternately, if we have a String that we expect contains text that can be interpreted as a number, we can use methods of the Integer and Double classes to do the conversion:
String s1 = "23"; int i1 = Integer.parseInt(s1); String s2 = "-3.5"; double d2 = Double.parseDouble(s2);
Note that these would throw NumberFormatExceptions if the String passed as their parameters cannot be converted to the desired numerical format.
A very common situation where String-to-number conversions are needed is when numbers are entered through graphical user interface components, such as popup windows created using the JOptionPane methods.
Java API Documentation: javax.swing.JOptionPane
String response = JOptionPane.showInputDialog("Enter an integer."); int theInt = Integer.parseInt(response);
Practice Programs
More on the WordsFromText program:
For the input file below:
It's not impossible I used to bullseye womp rats in my T-16 back home they're not much bigger than two meters Then man your ships And may the Force be with you
my program prints:
Encountered 32 words. Shortest: I Longest: impossible First: And Last: your
Your program should use these rules, at a minimum:
http://
" and has at least one ".
" after that prefix, but not as the
first character of the part after the prefix.
@
" followed by at least one ".
" somewhere
after the "@
", but again not first. There cannot be a second "@
".
Hint: String methods such as indexOf and substring are likely to be helpful.
Here are some sample interactions with my reference solution to this program:
Input string? me@here.com Could be an email address. Input string? http://x.com Could be a URL. Input string? hithere!! Doesn't look like either. Input string? http://me@here.com Could be a URL. Could be an email address. Input string? courses.teresco.org Doesn't look like either. Input string? me@here@there.com Doesn't look like either. Input string? me@http://strose.edu Could be an email address. Input string? cs252@http:// Doesn't look like either.
Submitting
Before 11:59 PM, Monday, February 15, 2016, submit your lab for grading. To complete the submission, email a copy of your lab (a .7z or .zip file containing your project directory) to terescoj AT strose.edu.
Grading
This assignment is worth 40 points, which are distributed as follows:
> Feature | Value | Score |
WordsFromText correctness | 15 | |
GuessingGame correctness | 5 | |
WhatIsIt correctness | 20 | |
Total | 40 | |