Week 9
Basic I/O; methods (functions); variable scope; strings.
Strings
We’ll see examples of a few mini-languages used within Java (and many other
programming languages) when dealing with String
s.
- String formatting: see Java string formatting
- Regular expressions: see Java regular expressions
First example:
public static void main(String[] args) {
// Read a string and do the following:
// 1. Print the original string.
// 2. Print the string's length.
// 3. Print the string in lower case.
// 4. Print the string in upper case.
// 5. Print the string with the first letter capitalized.
// 6. Print the number of 'a's in the string.
// 7. Print the string with all 'a's replaced by 'b's.
// 8. Print the string with all consecutive 'a's replaced by a single 'a'.
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.format("1. %s\n", s);
System.out.format("2. %s\n", s.length());
System.out.format("3. %s\n", s.toLowerCase());
System.out.format("4. %s\n", s.toUpperCase());
String firstLetter = s.substring(0, 1);
String rest = s.substring(1);
System.out.format("5. %s\n", firstLetter.toUpperCase() + rest);
int acount = 0;
for (int i = 0; i < s.length(); i = i + 1) {
char c = s.charAt(i);
if (c == 'a')
acount = acount + 1;
}
System.out.format("6. %s\n", acount);
String r = s.replace("a", "b");
System.out.format("7. %s\n", r);
String r2 = s.replaceAll("a+", "a");
System.out.format("8. %s\n", r2);
}
Processing input
Reading
Java for Everyone, chapters 4-5. Chapter 4 is more review of concepts we covered when using Processing.