RU beehive logo ITEC dept promo banner
ITEC 120
2010fall
ibarland

homeinfolectslabsexamshws
tutor/PIsObject120 + its docsjava.lang docsjava.util docs

lab08a
Reading input from the terminal
java.util.Scanner

We can have our programs read input from the terminal by using a java.util.Scanner:

java.util.Scanner scnr;

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

System.out.print( "Please enter your favorite color: " );
String userFaveCol;
userFaveCol = scnr.next();   // Ask scnr for the next word it reads.  (Throw away any whitespace.)

System.out.print( "Please enter your age: " );
int userAge;
userAge = scnr.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.

Full docs: java.util.Scanner (see the navbar at the top of each page).

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

class TempConverter2 {

  static double fahrToCelc( double tempF ) {
    return (tempF - FAHR_FREEZING) * CELC_PER_FAHR;
  }

  static double FAHR_FREEZING =  32.0;
  static double FAHR_BOILING  = 212.0;
  static double CELC_PER_FAHR = 100.0 / (FAHR_BOILING - FAHR_FREEZING);


  static void testInteractive() {
    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.print( "What is your name? " );
    String usersName;
    usersName = s.next();

    double temperature;

    System.out.print( "Please enter a temperature in Fahrenheit: " );
    temperature = s.nextDouble();
    System.out.println( "Hi " + usersName + "; " 
                      + temperature + "°F = " + fahrToCelc(temperature) +  "°C." );

    System.out.print( "Please enter a temperature in Fahrenheit: " );
    temperature = s.nextDouble();
    System.out.println( "Hi " + usersName + "; " 
                      + temperature + "°F = " + fahrToCelc(temperature) +  "°C." );

    System.out.print( "Please enter a temperature in Fahrenheit: " );
    temperature = s.nextDouble();
    System.out.println( "Hi " + usersName + "; " 
                      + temperature + "°F = " + fahrToCelc(temperature) +  "°C." );
     
    System.out.println( "As Mark Twain noted, " + usersName + ",\n"
                      + "everybody complains about the weather,\n"
                      + "but nobody every does anything about it." );
                      // Quote by Mark Twain.

    // 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.
  }



  static void testTempConverter2() {
    System.out.println( "Actual: " + fahrToCelc(32) );
    System.out.println( "Expect: " + 0.0 );
    System.out.println( "Actual: " + fahrToCelc(212) );
    System.out.println( "Expect: " + 100.0 );
    System.out.println( "Actual: " + fahrToCelc(-40) );
    System.out.println( "Expect: " + -40.0 );
    System.out.println( "Actual: " + fahrToCelc(98.6) );
    System.out.println( "Expect: " + 37.0 );
  }
}

Your Task: Write a function named, say, testStudentInteractive which does the following (reminiscent of how TempConverter#testInteractive above): creates a new student named Blanche Slayte (ID: 2010-10-18), and then does the following four times: prompts the user to enter a grade and a number of credit-hours, updates Blanche's information with this info, and then prints out her gpa.

What a Scanner is doing for you

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)

Optional: Formatting output

We'd like to format our output more nicely, to get rid of the long decimals. There is a function java.lang.String#format which splices numbers into a "format" string:

System.out.println( String.format( "Hi %s; %f fahr = %.2f celc.", usersName, temperature, fahrToCelc(temperature) ) );
You can read more about format in the docs for class String. The book also talks about a more general (object-oriented) approach for handling formatting, java.text.DecimalFormat though I find it to be overkill for the code I write.

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.      

homeinfolectslabsexamshws
tutor/PIsObject120 + its docsjava.lang docsjava.util docs


©2010, Ian Barland, Radford University
Last modified 2010.Oct.19 (Tue)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme