CS 1: Lecture 6 – String
Dear students,
If this class was a book, the chapter we’re in right now is Computer as Calculator. I’d mentioned that computers got their start in the world of mathematics. Why exactly did computers start with the mathematicians?
The good news is that numbers are not the only thing that computers are good at crunching. They are also really good at crunching communication. They can send out our words (and propaganda) as fast as electricity travels. So, today we’ll talk about text. We introduce the String
class, which stands for a String
of characters.
First, we should make it clear that there are two types of citizens in Java: primitives and objects. Primitives are the dregs of society, they are simple numbers or letters or trues or falses. Their type names are all lowercase. Objects are bigwigs, having their type names capitalized. We create them in slightly different ways:
Type myObject = new Type(...); type myPrimitive = ...;
We also act upon them in different ways. Primitives are bullied about with operators like +
and %
. Objects are deferentially asked to do things through their methods:
prim1 + prim2 + prim3 // operators object.pleaseDeleteAllMyFiles() // method call
So, we can make this analogy:
operators : primitives :: methods : objects
The data type of an object is its class
. We’ve formally met one object class so far: Scanner
. Now it’s time to meet String
. Based on our discussion above, we create a String
like this:
String name = new String("Frank Lee");
The thing is, we use String
s so often, the Java folks have allowed us to say it more compactly:
String name = "Frank Lee";
Now, we could jump immediately into describing the superpowers that String
confers to you, but I’d rather we get a feel for what kinds of things we do with text. Let’s play a little game. Here goes. I’m thinking of a String
. You need to figure out what it is by asking only yes or no questions. Can you do it?
It’s likely you are going to ask me questions that correspond to methods in the String
class. If so, we have achieved our purpose.
We’ll discuss how String
s are laid out in memory, how we can index into them, extract substrings and so on, through a few example problems:
- You ask the user for a credit card number. Print it back to the console with all but the last four digits as asterisks.
- Students and teachers get a discount at your website. How can you tell if someone’s a student or teacher?
- You ask 125 people for their UWEC username—and username only. All of them append
@uwec.edu
anyway. How can you clean up one such input? - You are writing a MUD and want to respond only to the commands
north
,south
,east
, andwest
. But the players are entering in all sorts of perversions of this likeNORTH
andeast
(with trailing spaces). How can you “canonicalize” their input to what you expect? - Display at most 10 characters of a customer’s first name.
- Ask the user for a mod problem (
100 % 3
) and compute its value.
Notice that calling methods on String
s is different than calling methods of the Math
class:
char first = name.charAt(0);
double score = Math.floor(points);
In the case of length
, we call this method on an instance of the String
class. There may be many instances of String
s in our program, and length
will give back a different result for each one. With floor
, there’s no instance of Math
. We call it directly on the class.
This difference is what static
refers to. Math.floor
is a static
method. String.charAt
is not.
If something is static, like static electricity, it is not moving. It is in stasis. The Math
class is not moving behind the scenes. String
s, however, are a moving target, as each String
will have different contents.
Here’s your TODO list of things to complete before next class:
- Homework 1 is due before Friday. I will grade Friday. Visit office hours now, both mine and the TAs, if you need to think out loud with someone. You are likely to encounter SpecChecker and Git issues—resolving them is as much a part of the homework as writing the code. Give yourself enough time to actually learn the ideas of the assignment. Do not wait until the last minute; I will not be around to support last-minute scrambling.
- Lab 2 is posted. You are always invited to work ahead.
See you next class!
P.S. It’s time for a haiku!
They’re just trolls, but still
The comments of the web burn
Leaving us inchar
s
P.P.S. Here’s the code we wrote together in class…
CreditCard.java
package lecture0918;
import java.util.Scanner;
public class CreditCard {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Watz ur #? ");
String ccn = in.nextLine();
String last4 = ccn.substring(12);
System.out.println("************" + last4);
}
}
EduDiscount.java
package lecture0918;
import java.util.Scanner;
public class EduDiscount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Email: ");
String address = in.nextLine();
boolean isDiscounted = address.endsWith(".edu");
System.out.println(isDiscounted);
}
}
EmailCleanerUpper.java
package lecture0918;
import java.util.Scanner;
public class EmailCleanerUpper {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Email: ");
String address = in.nextLine();
int indexOfAt = address.indexOf('@');
String username = address.substring(0, indexOfAt);
System.out.println(username);
}
}
CreditCardMasker.java
package lecture0918;
import java.util.Scanner;
public class CreditCardMasker {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Gimme your CCN, now: ");
String ccn = in.nextLine();
ccn = ccn.replace(" ", "");
ccn = ccn.replace("-", "");
ccn = ccn.replace(".", "");
// ccn = ccn.replaceAll("\\D", "");
String last4 = ccn.substring(12);
System.out.println("************" + last4);
}
}
MUD.java
package lecture0918;
import java.util.Scanner;
public class MUD {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("> ");
String command = in.nextLine();
command = command.toLowerCase().trim();
// command = command.trim();
System.out.println("|" + command + "|");
}
}
Modulator.java
package lecture0918;
import java.util.Scanner;
public class Modulator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("> ");
String expression = in.nextLine();
int whereModAt = expression.indexOf('%');
String left = expression.substring(0, whereModAt);
String right = expression.substring(whereModAt + 1);
int a = Integer.parseInt(left.trim());
int b = Integer.parseInt(right.trim());
System.out.println(a % b);
}
}