Radford University ITEC

ITEC120

hodge-podge: output, arithmetic, variables

Sep.11 Conference

Announcement, also on WebCT:
Status: Sent September 6, 2006 4:09 PM
If you want to participate in one of the university events for the 9/11 conference, you can be excused from Monday's class.

You will need to bring a paragraph which

If you're not at some event for the conference, then I'll see you in class Monday morning!
--Ian

Reading: all of Chapter 2 (not just the sections listed in hw02), except for the sections on graphics (whose pages have green trim).
These notes are my take on those same topics, just with different emphasis.

(Spend 20min discussing hw02.)

More about Strings; Output

The meaning of quote

Compare:

Love is a four-letter word.
"Love" is a four-letter word.
What is the difference? The first is a very cynical comment about relationships. The second is a very obvious, boring comment about words in the dictionary.

Quotation marks mean: suppress the usual conversion from a word to its meaning (from syntax to semantics). So when you read about a cat, you think of a furry four-legged beastie. But "cat" in quotation marks is talking about the sequence of letters C-A-T, not four-legged furballs.

A speech addressed to a person who isn't there is known as an “apostrophe”.

Guideline: if you can replace a word with a synonym, then it should not be in quotes.

When I was in kindergarten, I couldn't pronounce “chair”.
(Note that the sentence has nothing to do with sitting-platforms, though it does include the word for a sitting-platform.) In English, note that mottos are often in quotes, because they're like a trademark -- you can't replace it with a synonym and still have the motto or trademark.

When you quote somebody, you are referring to their exact words, and you are not allowed to paraphrase or use synonyms: (Although presumably the purpose for repeating their exact words pertains to the meaning of those words, so here you do expect people to pretend they are listening to those exact words, and have them reference the meaning of those words.)

In java: you write Math.PI and Java looks up the value of that name in the environment. (Any other expression which evaluated to 3.141592653589793 would do just as well.) But if you write "Math.PI", Java doesn't look anything up, and instead is talking about the text itself; you couldn't replace it with any other letters between the quotation marks without changing anything.

(In English, quotes are typically used as a sarcastic comment indicating that the word is being used is inappropriate:

The “collateral damage” mentioned in the report was a civilian family.
This usage of quotation marks has strayed a bit from the original meaning, but still retains the trait that it draws attention to the particular choice of words being used.

Escape sequences

Escape characters: Java recognizes string literals because they start with a quotation mark ("), then have the desired text, and the end is delimited by another quotation mark. But if a quotation mark always indicates the end of a String, does that mean it's impossible to have a string containing a quotation mark?

See book for table of escape characters. But really, \n is the most common one I ever use, and occasionally \" and \\. The rest you can safely forget and re-look-up, should the need ever arise.

Output

There is a function built-in to java, which takes as input a String, and returns nothing at all. ?! How could this ever be helpful? Well, it also has a side-effect: it prints that string on the output device (a screen, or perhaps printer). System.out.println

Note that it does not return anything, and therefore it doesn't play well with others -- you can't use any return value from it to pass on to other functions. Compare this to functions like petStoreMessage, which return a string, allowing us to do anything we want with the result: print it, or include it in an email message, or put it into a web page, or ...

Arithmetic

Input

The complement of writing to System.out.println is reading from System.in, although this time it's more complicated than just calling a read method. The reason is, if you read straight from the keyboard, you get raw characters: the user types in 33 44 followed by a return, System.in just gives you six characters, that's all. You need an expert who is good at reading that sequence of characters, and can recognize it as a sequence of entire numbers.

Java provides such an input-reading specialist -- a Scanner who will read the input and group characters into (say) numbers and words for you. Scanners are actually defined off in a standard utility package called java.util, so its full name is java.util.Scanner. A bit verbose, but it works:

java.util.Scanner s = new java.util.Scanner( System.in );
s.nextInt();
s.nextInt();
What other things can you ask a Scanner to do, besides asking it for the nextInt()? Guess a name, and give it a try! For a more complete list,1 create a Scanner (by typing new java.util.Scanner(System.in) instance in BlueJ's code pane), drag the resulting little-red-rectangle it to the bench, and then right-click on the instance to see its methods.

Exercise: Create a new Scanner and give it the name scan; then evaluate: scan.nextInt() - scan.nextInt().

Variables

We've seen several types of variables so far: named constants, and local variables to avoid duplicated code:

There is a another use of local variables: give a name to the result of a (small) computation, when building up a bigger computation. Here's an example: recall crustArea, back from our class PizzaServer example:

  double crustArea( double diam ) {
    return pieArea( diam )  -  pieArea( diam - 2*CRUST_WIDTH );
    }
Here is an alternate way of writing the same function:
  double crustArea( double diam ) {
    final double totalArea = pieArea( diam );
    final double toppingArea = pieArea( diam - 2*CRUST_WIDTH );

    return totalArea - toppingArea;
    }
(Note the indentation, the use of plausible names, and even the way the spaces in “diam - 2*CRUST_WIDTH” help reflect the order-of-operations.)

In fact, we can take this idea of using variables to store sub-computations even further:

  double crustArea( double diam ) {
    final double totalArea = pieArea( diam );

    final double toppingDiam = diam - 2*CRUST_WIDTH;
    final double toppingArea = pieArea( toppingDiam );

    final double crustArea = totalArea - toppingArea;

    return crustArea;
    }
Which of these three versions do you prefer best? Which is most understandable to you? Discuss.

Exercise: Take

  int gb2albums( double discSpace ) {
    return double2int( Math.floor( gb2min(discSpace)/MINS_PER_ALBUM ) );
    }
and use some final variables to compute partial results. Be sure to use descriptive names! (Although all-caps are not needed, because these variables, while constants, don't live forever; they only exist while gb2albums is at work.)

Compare/discuss/vote on:

   double miles = promptForDouble( "How far can your car go on a full tank (in miles)?" );
   double gallons = promptForDouble( "How many gallons does your gas tank hold?" );
   return miles/gallon;
s
   return   promptForDouble( "How far can your car go on a full tank (in miles)?" )
             / promptForDouble( "How many gallons does your gas tank hold?" );

Discuss: Once we create a Scanner and name it2 myScanner, what is the difference between
myScanner.nextInt() * myScanner.nextInt()
and
int n = myScanner.nextInt();
n * n
Note that mathematicians don't want to call nextInt a true function, since it can give different answers back in an unpredictable3 way. (Compare this to, say, Math.sqrt(25.0), which always returns 5.0 no matter how many times you call it.)

Next time: Variables which actually vary!


1 Critical thinkers might wonder: why can't System.in provide a method nextInt directly? Indeed, that would be simpler. The answer is partly historical (they didn't provide such nice functionality in the first version of the library), and partly that Scanner does enough special-purpose work on tokenizing Strings that it warrants being its own separate class (that is, a new type of expert).      back

2java.util.Scanner myScanner = new java.util.Scanner( System.in );      back

3 The truly sly mathematicians point out that if you consider “what gets typed on the keyboard” as an implicit input to any program involving System.in, then it does become a function again. These same mathematicians will claim that actually, System.out.println accepts not just a String, but also a screen (the before-snapshot), and that it returns a screen (an after-snapshot). This makes them happy, since true math functions are well-understood and can be reasoned about.      back


©2006, Ian Barland, Radford University
Last modified 2006.Sep.26 (Tue)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme