JamesMadisonUniversity

Computer Science Department


CS 139 Lab: Input and output in Java


Objectives:

Students will practice:
  • declaring and using variables
  • using concatenation operators
  • reading values from the keyboard
  • manipulating output

Background:

Java is a strongly typed language. In some cases, widening conversion may be done to make both operands the same type before the operation is carried out. In other cases, automatic conversion cannot be done. This lab explores some of these features while also exploring the Scanner class. You will find information about Scanner in chapter 2.13 of the text.

Key Terms:

Scanner
A Java provided class that enables us to do input functions.
concatenation
Process of combining two strings
data type
The kind of data that a container can hold.
Strongly typed
A language in which containers may only be declared to be of one type and they can only hold that type. Operations must use the same data types.

Materials:

Concat.java

Types.java

Prerequisites:

You should have viewed the Scanner tutorial or read the pertinent section in your textbook.

Part 1: Startup

Set up your programming environment for this lab. Create a folder on your n-drive and download the files found in the materials section.

Part 2: Two meanings of +

In Java, the symbol + can be used to add numbers or to concatenate strings. This lab illustrates both uses.

When using a String literal (a sequence of characters enclosed in double quotation marks) in Java the complete String must fit on one line. The following is NOT legal (it would result in a compile-time error).

    System.out.println ("It is NOT okay to go to the next line
in a LONG string!!!");

The solution is to break the long String up into two shorter strings that are joined using the concatenation operator (which is the + symbol). So the following would be legal.

    System.out.println ("It is OKAY to break a long string into "
+ "parts and join them with a + symbol.");

(Note how the continued line is indented one space to indicate it is a continuation line. Also note that the operator is placed at the beginning of the continuation line instead of at the end of the first line, to improve readability.)

So, when working with strings the + symbol means to concatenate the Strings (join them). BUT, when working with numbers the + means what it has always meant, add!

  1. Download the program Concat.java . Do not compile or run the program (yet).
  2. Unlike primitive data types (do you remember the 8 primitive data types?), Strings are Java classes just like the Hello program was a class. As such, it has methods or actions that can be done on Strings.
  3. This program uses the length method of the String class. length is a method that returns a value which, in this example, is the number of characters in sample. Or another way to read this is "sample's length".
  4. "Hand trace" the program. That is, act as if you were a computer and execute each statement in the program like a computer would. Draw storage boxes on a piece of paper to simulate variable/constant storage containers.
  5. Write the output your hand tracing produces on your paper.
  6. Compile and run the program. Compare your "expected result" with the "actual result".
  7. For each line where the "expected result" differed from the "actual result", do you understand why your prediction was wrong? If you cannot figure it out so you know for sure, ASK!

Correct the second output statement so blanks are printed around the 55. Recompile and run.

Before turning in this assignment, be sure to fill in the standard header information.

Part 3: Input in Java

  1. Download the program Types.java.
  2. Open it up in the editor of your choice.
  3. Read through the program, noticing the following new features:
    1. Scanner - The Scanner class provides a mechanism for reading in values from the keyboard (among other things).
    2. The very first line of the program is an import statement. This import makes the Scanner class available to this program.
    3. Before we can use the Scanner, we must make and instance of it. We call an instance of a class an object. So we need to create a Scanner object.
    4. So, we first declare a Scanner variable named keyboard. Then in the initializations, we instantiate or make a new Scanner object. The value in the parentheses is System.in which refers to standard system input or the keyboard.
    5. Whenever we expect the user of a program to enter something at the command line, we have to prompt them. The line System.out.print("Enter a number: "); is performing the prompt. When you run this program, the line will display, then the program will stop executing until the user enters a value on the command line. The line num1 = keyboard.nextInt(); is the place where the keyboard Scanner is reading what the user has typed in and assigning it to the variable num1.
    6. We then echo the value of num1 in the following line.
  4. Compile the program and execute it using any integer value for num1.  If you enter something that is not an integer the program will crash (have a run-time error);
  5. Now, duplicate the three lines at the end of the program and alter them to read a value into val1.  You will need to use the nextDouble() method instead of nextInt().
  6. Compile and execute the program with your changes.
  7. Finally, duplicate the last three lines and alter them to read a value into text.  You will need to use the nextLine() method instead of nextDouble(). NOTE: When reading in both numbers and text, you need to be aware that Scanner leaves in the new line character that you enter as return. When you read a number followed by text you need to have a single line which will consume the new line character. So you would need to add the line keyboard.nextLine(); after the prompt and before the actual read of the text value. See Gaddis, page 88-91.

Part 4: Data types and compatibility


The last part of the lab will have you practice with different data types. The three shown in this lab are the ones you will most commonly use. 
  1. Add a statement to the end of the program to assign the value found in text to the variable val1.  What happens when you try to compile it?
  2. Comment out that line (inline comments) and add a new line that assigns the value of val1 to num1. What happens when you try to compile it?
  3. Comment out that line and add a new line that assigns the value of val1 to val2. What happens when you try to compile it? Will it execute?
  4. Add a print statement to display the contents of val1 and val2 after the assignment.
  5. Add a statement to the end of the program to assign the value found in num1 to val2.  What happens when you try to compile it? Will it execute?
  6. Add a print statement to display the contents of num1 and val2 after the assignment.
  7. What can you say about compatibility among Java data types? In other words, when can you assign values of different data types to one another?

Part 5: Optional - The cast operation

Let's say that you wanted only the integer portion of the value in val1.  To do this, you must "cast" the value of val1 as an integer. Casting tells the compiler that it should treat the value as if it were the cast type. See an example in your book, section 2.7, Conversion between Primitive Data Types.
  1. Uncomment the line you created in Step 4.2 (assigning val1 to num1).
  2. Add a cast operation to convert val1's value to an integer.
  3. Compile and execute the program.

Part 6: Optional - Going further

  1. Look at Programming Challenges, number 1 in the back of Chapter 2.
  2. Write a new program called NameAgeIncome that will read in the three values described and print them back out again as described in the assignment.
  3. The income will print with as many decimal places as there are in the number with a minimun of 2. How can you format the number to print it nicely (in currency format). Hint: Loook for the DecimalFormatting class or printf.


Updated 09/12/11 (nlh)