RU beehive logo ITEC dept promo banner
ITEC 120
2008spring
ibarland,
jdymacek

homeinfoarchiveexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lab11a
Scanner
reading info from the keyboard (and more)

We saw last time that we could make a list holding Doubles.

java.util.LinkedList<Double> dubs;

dubs = new java.util.LinkedList<Double>();

dubs.add( new Double(1.2) );
dubs.add( new Double(3.4) );
dubs.add( new Double(5.6) );

dubs.size()
dubs.toString()

dubs.get(1).toString()
dubs.remove(1)
dubs.get(1).toString()

dubs.size()
dubs.toString()

dubs.contains( new Double(1.2) )       // “dubs, do you contain ...”
Your first task Repeat all the above steps, but instead of a list-of-Doubles, make a list-of-Dogs. (Make a copy of your old lab project, or use lab08a's Dog/Kennel .jar file.)

Can you explain the last result, for contains? What method does contains use, to determine if two Dogs are the same?

Reading input: Scanner

Reading a number typed in at the keyboard is more complicated than just calling a read method. The reason is, if you read straight from the keyboard, you get raw characters. Suppose somebody has typed “33   hi 44.4” followed by a return, then reading the keyboard merely gives you a dozen characters or so. If you want to convert some of those characters into numbers, and if you want to ignore skip over multiple spaces, then you need an expert who is good at reading that sequence of characters, and who can tokenize it -- turn it into a sequence of an int, a word, and a double.

Java provides such a specialist -- class java.util.Scanner. A Scanner reads characters from the keyboard (or a file, or anywhere)

java.util.Scanner s;

// Make a new Scanner which reads input from the keyboard (System.in):
s = new java.util.Scanner( System.in );

System.out.print( "Type in your favorite color: " );
String userFaveCol;
userFaveCol = s.next();   // Ask s for the next word it reads.  (No spaces.)

System.out.print( "Type in your age: " );
int userAge;
userAge = s.nextInt();   // Ask s for the next int it reads.

System.out.println( "What, a " + userAge + "-year-old who likes " + userFaveCol + "?!" );
Note: While methods like next and nextInt are waiting for you to type something at the console window, the computer will otherwise just sit there, with BlueJ's (red-and-white) progress bar idling. The program will “block” until you have typed something and hit enter.

Of course, things like this can go inside a method, no problem:

  public static void smallTalk() {
    java.util.Scanner s;         // Declare a variable.

   /* make a new Scanner which reads from the keyboard (System.in): */
    s = new java.util.Scanner( System.in );

    System.out.println( "Type your favorite color (one word): " );
    String usersName;
    usersName = s.next();
    System.out.println( "Howdy, " + usersName + "." );

    System.outprintln( "Type your age." );
    int usersAge;
    usersAge = s.nextInt();
    System.out.println( 

    // Note: No return value, from this function --
    // printing results to the console means they're gone forever,
    // and we can't pass those strings to other methods for further
    // processing; we'd need to *return* the string for that.
    }

Task: Write a method createDogInteractive: This method prompts the user for a dog's name and its age, creates a new Dog as indicated, and returns that new Dog.

Back to lists

Task: Complete the following method, inside class Dog. Complete this code, and test by calling it on some particular list of three Dogs.

  /** Return the sum of the age of each dogs in a given list.
    * @param someDogs a list of exactly 4 dogs.
    * @return the sum of the age of each dog in someDogs.
    */
  int totalAge( java.util.LinkedList<Dog> someDogs ) {
    int totalSoFar = 0;
    Dog d;   // Over time, this variable will refer to *each* dog in the list(!)

    d = someDogs.get(0);      // d now refers to the dog at index 0.
    totalSoFar = totalSoFar + d.getAge();   /* totalSoFar now contains dog0's age. */

    d = someDogs.get(1);     // d now refers to the dog at index 1.
    totalSoFar = totalSoFar + 0;  /* MODIFY THIS LINE, so that totalSoFar now 
                                    contains dog0's age *plus* dog1's age. */

    /*  ADD TWO MORE LINES, 
     *  so that totalSoFar contains dog0's age plus dog1's age plus dog2's age. 
     *	 You are encoruaged to cut-and-paste.  (We'll see a better way tomorrow.)
    */

    /*  ADD TWO MORE LINES, 
     *  so that totalSoFar contains each dog's age, all added together.
     *	 You are encoruaged to cut-and-paste.  (We'll see a better way tomorrow.)
    */


    return totalSoFar;
    }

Optional: reading files and web pages

By the way: a Scanner can read information from more than just the keyboard, System.in. You can also make Scanners which read from files, or even from web pages.


1 In this case, if you try it out, you realize that web pages are written in html; in html the notion of the “next word” is different from where the next whitespace occurs. Indeed, people have written specialized classes which extend Scanner to so that the next method returns the next word in a way that is appropriate for html.      

homeinfoarchiveexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2008, Ian Barland, Radford University
Last modified 2008.Apr.02 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme