Valdosta State University



CS 1302 – Chapter 4 (Review)Mathematical Functions, Characters, & StringsReference Sections 4.3, 4.4, 4.6OverviewIn this review material we consider how to use some methods from the Character and String classes:4.3 – Character Data Type & Operationschar is a primitive data type. A character literal is specified with single quotes. For example:char code = 'B';char[] codes = {'C','a','G','T','f'};right381000The Character class defines a number of useful static methods as shown in the class diagram on the right. It should be obvious what they do. A note on the syntax of the class diagram:char code = 'a';boolean isChar = Character.isLetter(code);code = Character.toUpperCase(code);Comparing Characters – Since characters are represented internally as numbers, we can compare characters with: =, !=, <, <=, >, >=. Example – Write a method, makeUpperCase that accepts a character array and makes all the elements upper case.public static void makeUpperCase(char[] codes) {for(int i=0; i<codes.length; i++) {if(Character.isLowerCase(codes[i])) {char c = Character.toUpperCase(codes[i]);codes[i] = c;}}}Best Practices:The name of an array should always be pluralMethod and variable names use camel caseA method that returns a boolean should begin with a “is”, as in isLowerCase. Sometimes these prefixes are more suitable: “has”, “can”, “should”. This is also true for boolean variables.A boolean method (or expression) returns true or false. Thus, in an if statement you should not check to see if it is true (or false). For example:PreferredNot Preferredif(Character.isLowerCase(codes[i]))if(Character.isLowerCase(codes[i])==true)if(!Character.isLetterOrDigit(c))if(Character.isLetterOrDigit(c)==false)Write a method, countAAndZ that accepts a character array and returns the number of characters in the array that are either ‘A’ or ‘Z’.public static int countAAndZ(char[] codes) {int count = 0;for(int i=0; i<codes.length; i++) {char c = codes[i];if( c=='A' || c=='Z' ) {count++;}}return count;}4.4.1-4.4.4 – Strings 1right508000String is a class in Java. In this chapter, we study the methods shown in the class diagram on the right. We usually create a String by assigning it to a string literal:String s = "buffalo";However, we can use the constructor:String s = new String("buffalo");We use an escape sequence to represent special characters. In Java (and many languages) this is a backslash followed by a character (or digits). Several useful escape sequences are:Escape SequenceName\nNew line\tTab\\Backslash\”Double quoteFor example:CodeOutputString msg = "The \"first\"\nThe second ";System.out.println(msg);The "first"The secondString Class – Know these methods: length, charAt, concat, toUpperCase, toLowerCase, trim. For example:MethodDescriptionlength():intReturns the length of the string, the number of characters.charAt(i:int):charReturns the character at index i in the string.trim():StringReturns a string whose value is this string with any leading or trailing whitespace removed.toUpperCase():StringReturns a string whose value is this string and with all the characters being converted to upper case.toLowerCase():StringReturns a string whose value is this string and with all the characters being converted to lower case.concat(s:String):StringReturns a string whose value is this string with s concatenated to the end. Usually we just use the “+” operator to concatenate strings. Both of these are equivalent:String s1 = "anteater";String s2 = "buffalo";String s3 = s1 + s2;String s4 = s1.concat(s2);Example – Write a method, countUC that accepts a string and returns the number of upper case letters in the string.public static int countUC(String str) {int count = 0;for(int i=0; i<str.length(); i++) {if(Character.isUpperCase(str.charAt(i))) {count++;}}return count;}Example – Write a method, isLastCharSame that returns true if the last character in each of two input strings is the same.public static boolean isLastCharSame(String s1, String s2){char e1 = s1.charAt(s1.length()-1);char e2 = s2.charAt(s2.length()-1);return e1==e2;}Example – Write a method that returns whether a string is a palindrome. public static boolean isPalindrone( String s ){int left = 0;int right = s.length()-1;for(int i=0; i<s.length()/2; i++, left++, right--){if( s.charAt(left)!=s.charAt(right))return false;}return true;}Homework: Write a method, getUC that accepts a string and returns a string with just the upper case letters. For example: getUC(“aBcDe”) would return “BD”Write a method, numsFirst that accepts a string and returns a string with all the digits in the input string first followed by all the letters. For example: “1a2b3c” returns “123abc”, and “xyz 456” returns “456xyz”.Write a method, isNumber that accepts a string and returns true if the string is an integer and false otherwise. Hint: all the characters need to be digits.Write a method, countVowels that accepts a string and returns the total number of vowels (a,e,i,o,u) in the string. Hint: (a) define a char array in method that defines the five vowels, (b) loop over each character in string, and for each character, loop over vowels array to see if one of them matches the character. For example:countVowels("Thgvlm")=0countVowels("Thez")=1countVowels("eaterallyou")=6Write a method, isPalindrone2 that accepts a string and returns whether the string is a palindrome ignoring spaces. For example: “a bc cba” returns true. Note that this example has 1 space between and the “a” and “b” and 2 spaces between the two “c”s. Hint: write a helper method to remove the spaces from a string and then call isPalindrone written in the notes above.4.4.7 – Strings 2 – Comparison MethodsThese are several comparison methods in the String classMethodDescriptionequals(s:String):booleanReturns true if s has exactly the same contents as this string.contains(s:String):booleanReturns true if s is in this string. Note: there is not an overload that accepts a pareTo(s:String):intReturns a negative integer if this string is lexicographically less than s, a positive integer if this string is greater than s, and 0 if they are the same.Characters are represented by Unicode values (integers). The lexicographic order of these are: 0, 1, 2, …, A, B, C, …, a, b, c. Note that the upper case characters are before the lower case characters. The compareTo(s:String) method starts at the beginning of this string and s and finds the first character that is different between the two. It uses this character to see which string is smaller. It is easier to see with the examples below. Finally, it returns 0 if the two strings are equal.String s1 = "ant";String s2 = "fox";String s3 = "alpaca";String s4 = "ant";System.out.println(pareTo(s2)); // -5System.out.println(pareTo(s1)); // 5System.out.println(pareTo(s3)); // 2System.out.println(pareTo(s4)); // 0As noted above, the upper case characters occur before the lower case letters. For example:String s1 = "fox";String s2 = "Fox";System.out.println(pareTo(s2)); // 26The compareToIgnoreCase(s:String) method is the same as compareTo except that it ignores case differences. For example: String s1 = "fox";String s2 = "Fox";String s3 = "FOx";String s4 = "falcon";System.out.println(pareToIgnoreCase(s2)); // 0System.out.println(pareToIgnoreCase(s4)); // 14Do NOT use “==” to compare the contents of two strings. When you use “==”, the JVM checks to see if the two objects occupy the same location in memory, not to see if the contents of the strings are the same.In other words, do this:Do This:Not This:if(s1.equals(s2)) if(s1==s2) Homework: Write a method, countStrings, that accepts an array of strings and and another string, key. The method should return the number of strings in the array that have the same contents as key.Write a method, findSmallestString, that accepts an array of strings and returns the smallest, lexicographically, string ignoring differences in case.4.4.8 – Strings 3 – Substring MethodsThe String class has methods for returning a substring:MethodDescriptionsubstring(beg:int):StringReturns the substring in this string that beings at index beg and extends to the end of the string.substring(beg:int,end:int):StringReturns the substring in this string that begins at index beg and extends to the character at index end-1. Thus, the length of the returned string will be end-beg.For example:String s1 = "anteater";String s2 = s1.substring(3);// "eater"String s3 = s1.substring(3,6);// "eat"Homework: Write a method, trimFirstAndLast that accepts a string and returns a string with the same contents as the input string except that the first and last characters are removed. Must use substring, can’t use charAt. You can assume the input string has at least 2 characters. Hint: the method body is one line of code. For example:trimFirstAndLast (“uengines”) returns: “engine”Write a method, reverseHalf that accepts a string and returns a string with the right half of the input string first, followed be the left half of the input string. Must use substring, can’t use charAt.reverseHalf(“abcdef”) returns: “defabc”reverseHalf(“abcde”) returns: “cdeab”As the later example shows, if the string has odd length then the middle character is considered the first character in the right half. Write a method, getOutside that accepts a string and two integers, loc1 and loc2. The method should return a string composed of the characters that are not between (inclusive) loc1 and loc2. Must use substring, can’t use charAt. For example:getOutside(“DogzqfgZebra”,3,6) returns: “DogZebra”If loc1>loc2 or loc1 or loc2 is not a valid position in the string, then return an empty string.A string, s1 begins with an integer product code followed by a description. Write a snippet of code that uses the substring method to create a new string containing just the description. Example: s1=”4432Night Vision Googles” would produce s2=”Night Vision Googles”. You will need charAt, but you must also use substring.Write a method, everyOther3Tuple that accepts a string. You can assume this string has a length that is a multiple of 3. The method should return a string that contains every other 3-tuple. For example:everyOther3Tuple("abc")="abc"everyOther3Tuple("abcVVVdef")="abcdef"everyOther3Tuple("abcVVVdefTTT")="abcdef"everyOther3Tuple("abcVVVdefTTTghi")="abcdefghi"4.4.9– Strings 4, Substring Location MethodsThese methods in the String class return the location of an input string inside this stringMethodDescriptionindexOf(c:char):intindexOf(s:String):intReturns the index of the first occurrence of c (s) in this string or -1 if not found. indexOf(c:char,from:int):intindexOf(s:String,from:int):intReturns the index of the first occurrence of c (s) in this string which occurs at or after the index from, or -1 if not found.lastIndexOf(c:char):intlastIndexOf(s:String):intReturns the index of the last occurrence of c (s) in this string or -1 if not found. lastIndexOf(c:char,from:int):intlastIndexOf(s:String,from:int):intReturns the index of the last occurrence of c (s) in this string searching backwards starting at from.For example:String s1 = "anteater";anteater01234567int a = s1.indexOf('e');// 3int b = s1.indexOf("ate");// 4int c = s1.indexOf("bill");// -1int d = s1.indexOf("te", 3);// 5int e = s1.lastIndexOf("te");// 5int f = s1.lastIndexOf('a',3);// 0Example – Write a method, combine that accepts a string. This string contains two substrings separated by a comma. The method should return the two substrings concatenated. Example: “abc,def” returns “abcdef”.public static String combine(String s1){int pos = s1.indexOf(',');String substr1 = s1.substring(0, pos);String substr2 = s1.substring(pos+1);return substr1 + substr2;}Example – Write a method, countDotCom that counts how many times the sequence “.com” appears in an input string. For example: “abc.co .com pp. f” returns the value: 3. public static int countDotCom(String val){int count=0;int beg=0;while(beg<=val.length()-4) {int pos = val.indexOf(".com", beg);if(pos==-1) return count;count++;beg=pos+4;}return count;}Example – Write a method, uniqueChars that accepts a string and returns a string with exactly one instance of each character from the input string, in the order they occur. For example: “abbcKczza” returns “abcKz”. public static String uniqueChars(String s) {String result = "";for(int i=0; i<s.length(); i++) {char c = s.charAt(i);if(result.indexOf(c)==-1)result += c;}return result;}Homework: A string contains three substrings separated by a comma. Write a method, combine3 that accepts such a string and returns the three substrings concatenated. Example: “ab,cdefg,hi” returns “abcdefghi”.combine3("abc,def,ghi")="abcdefghi"combine3("1,2,3")="123"combine3("Coding ,is , cool")="Coding is cool"combine3(",ab,de")="abde"combine3(",,aab")="aab"combine3("abc,,4")="abc4"Write a method, findFurthestLocation that accepts a string and an array of characters. The method should return the furthest location in the string where one of the characters in the array occurs. For example:findFurthestLocation(abcdeaeafdah,[e, a, d])=10 // ‘a’ was the furthestfindFurthestLocation(abcdeaeafdah,[q, e, z])=6 // ‘e’ was the furthestfindFurthestLocation(abcdeaeafdah,[1, 2, 3])=-1 // none were foundWrite a method, findLocations that accepts a string and a character. The method should return the an array with the locations of the first 5 occurrences of the character in the string. If there are less than 5 occurrences, then -1 should be used to fill the return array. For example:findLocations(ab,a)=[0, -1, -1, -1, -1]findLocations(aab,a)=[0, 1, -1, -1, -1]findLocations(aba,a)=[0, 2, -1, -1, -1]findLocations(babbaabacde,a)=[1, 4, 5, 7, -1]findLocations(babbaabacdaffaage,a)=[1, 4, 5, 7, 10]Write a method, getVowels that accepts a string and returns a string that contains the vowels (a,e,i,o,u) in the input string. Only one occurrence of each vowel found should be returned. Hint: (a) define a string that contains all the vowels, “aeiou”, (b) loop over characters in string, (c) use indexOf to see if character is in vowels, (d) use indexOf to see if character is already in result, (e) can’t use contains as it only accepts a string. (f) there are other approaches. For example: getVowels("The dog ate cereal")="eoa"getVowels("aeiou")="aeiou"getVowels("a a a a e")="ae"getVowels("Zxylpls")=""Write a method, countOccurrences that accepts a two strings and returns the number of times the second string is found in the first string. For example:countOccurrences("circus time",'clown')=0countOccurrences("car is a car is a car but not a cat",'car')=3countOccurrences("atatat3",'at')=3 Consider a short version of a URL. For example the URL: “” is composed of “google” which is the domain name and “com” which is the top-level domain. A string contains a number of URLs each with the top-level domain, “com”. Write a method, domainNames that accepts such a string and returns a string of domain names separated by commas. For example:getDomainName("abcdefg")="")getDomainName("")="abc")getDomainName("")="a,b")getDomainName("")="a,b,c")getDomainName("")="google,nytimes,oracle")4.4.10– Conversion between Strings & NumbersTo convert a string which is a number, use one of these below. If the string is not a number (or the wrong type) a run-time error will result.String s1 = "48";int x = Integer.parseInt(s1);String s2 = "933.92";double y = Double.parseDouble(s2);To convert a number to a string, concatenate an empty string to the number:Number to StringCharacter to StringBoolean to Stringdouble x = 43.42;String s1 = String.valueOf(x);// OrString s2 = "" + x;char c = 'B';String s3 = String.valueOf(c);// OrString s4 = "" + c;boolean isValid = true;String s5 = String.valueOf(isValid);// OrString s6 = "" + isValid;Example – A string contains two integers separated by a comma. Write a method, sum that accepts such a string and returns the sum of the two integers.public static int sum(String s1){int pos = s1.indexOf(',');String strNum1 = s1.substring(0, pos);String strNum2 = s1.substring(pos+1);int num1 = Integer.parseInt(strNum1);int num2 = Integer.parseInt(strNum2);int sum = num1 + num2;return sum;}Example – A string contains two integers separated by a comma. Suppose the first integer is 3, you will write a method, subInteger that returns the integer composed of the first 3 digits in the second integer. Example: “3,12345” returns 123; “10,123456789012345” returns 1234567890.public static int subInteger( String s1 ){int pos = s1.indexOf(',');int len = Integer.parseInt(s1.substring(0, pos));int num = Integer.parseInt(s1.substring(pos+1, pos+len+1));return num;}Homework: A string contains a decimal number represented in European format (using a comma for the decimal separator. Write a method, convertToDecimal which accepts such a string and returns the United States representation of the number as a double. For example:convertToDecimal("3,333")=3.333convertToDecimal("0,123")=0.123convertToDecimal("222,0")=222.000A string contains two integers separated by a comma. Write a method, newNum that accepts such a string and returns the integer composed of the last digit of the first number and the first digit of the second number. For example: newNum("123,456")=34newNum("1,9")=19newNum("3,745")=37newNum("59,2")=92,A string contains a binary number. Write a method, binaryToDecimal that accepts such a string. The method should convert this number to its decimal representation and return it as a double. For example:binaryToDecimal("0000")=0binaryToDecimal("0001")=1binaryToDecimal("0011")=3binaryToDecimal("0111")=7binaryToDecimal("1101")=13binaryToDecimal("101010")=42A string contains two decimal numbers separated by an arithmetic operator (+,-,*,/). Write a method, artihmeticOperation that accepts such a string and returns the result of applying the operator to the two decimal numbers. For example:artihmeticOperation("3.333+6.667")=10.000artihmeticOperation("1-1")=0.000artihmeticOperation("3.333*6")=19.998artihmeticOperation("12.5/6.25")=2.0004.6 – Formatting Output – String.format methodThe String class defines the static method, format which returns a formatted string. The syntax is:String result = String.format( “format string” [, arg1, arg2, … ] );The format string is composed of string literals and format specifiers. Format specifiers define how to format the arguments. Example:Notice that there is one format specifier and that String.format returns the format string with the arguments substituted for the format specifiers.In the example above, there are 3 format specifiers“%s”SymbolMeaning%Signifies the beginning of a format specifier. sThe argument is a string or character“%d”SymbolMeaningdThe argument is an integer“%.2f”SymbolMeaning.2Round argument to two decimal placesfThe value is a floating (double) point numberA quick reference can be found here: – Write a method, formatArray that accepts an array of doubles and returns a string with the (a) numbers all in a single line each separated by a comma, (b) each number prefaced with, “ht=”, (c) two decimal places, and (d) no trailing comma. For example, the string that is returned will look like this:"ht=334.43, ht=5.89, ht=74.74, ht=8.50" public static String formatArray(double[] vals){String result = "";for(int i=0; i<vals.length; i++) {String num = String.format("ht=%.2f, ", vals[i]);result += num;}return result.substring(0,result.length()-2);}The format specifier for a floating point number can also take a comma to indicate to use a comma as the thousand’s separator:% , . decimals fExampleCodeOutputdouble salary = 78224.8230842;result = String.format("Salary=$%,.2f", salary);Salary=$78,224.82Note that the “$” is not a part of the format specifier, it is a string literal.Note that the format string is a String. This means that we can build it programmatically. For example:double num = 34.29368745;int numDec=3;String formatString = "ht=%." + numDec + "f, ";String formattedNum = String.format(formatString, num);Example – Write an overloaded method, formatArray from above that accepts an array of doubles and an integer. The integer represents the desired number of decimals in the output.public static String formatArray( double[] vals, int numDec ){String result = "";String formatString = "ht=%." + numDec + "f, ";for(int i=0; i<vals.length; i++) {String num = String.format(formatString, vals[i]);result += num;}return result.substring(0,result.length()-2);}The format specifier for a floating point number can also take the width (number of columns) of the space to print the number:% width . decimals fExample – The code below specifies a field width of 8 with 2 decimal places:CodeOutputdouble x = 498.57334;result = String.format("%8.2f", x);System.out.println(result);Notes:You can also use a “-“ flag in front of the width to left-justifyIf the specified field width is not wide enough, The JVM just expands it so that the whole number is displayed.Example – Suppose you have an array of doubles and all numbers are are less than 1000, you could print them with two decimals so that the decimals lined up using a width=6. For example:CodeOutputdouble[] vals = {498.56721, 4.3318, 27.921362};for(int i=0; i<vals.length; i++) {System.out.printf("%6.2f\n", vals[i]);}498.57 4.33 27.92Homework: Write a method, buildReport that accepts: an array of strings, names; an array of ints, ages; and an array of doubles, salaries. The size of each array is the same. The method should use String.format to build and return a string that shows each name, age, and salary on a single line in a format like this:Name: Jed, age:22, salary: $48,339.23Name: Keisha, age:33, salary: $68,992.92Name: Jaylen, age:44, salary: $121,042.04Write a method, formatWeights that accepts a double array of weights and an integer, n. The method will return a string with the weights all on a single line, separated by a single space, and having n decimals. Hint: a format string is a string, so you should build it programmatically. If n=3, then the result will look like this, for example:42.335 67.284 92.384 442.304 73.888Java defines a printf method which is used to achieve a formatted print. The syntax is:System.out.printf( “format string” [, arg1, arg2, … ] );The arguments to the method are identical to the arguments for String.format.Example:CodeOutputdouble x = 498.57334;double y = 6.1945;System.out.printf("x=%8.2f\ny=%8.2f", x, y);x= 498.57y= 6.19 ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download