CSU Banner

CS 163/164, 🀨 Fall 2019 🀨

Lab 4 - Scanners and Expressions

Thursday, Sep. 5th or Friday, Sep. 6th


Objectives of this Lab

  1. Learn how to interpret Java expressions,
  2. and create and use a Scanner to read keyboard input,
  3. and practice using System.out.printf to format output,
  4. and implement the quadratic formula in Java.

Interpret Java

Create a new Java Project named Exp, and make a class named Exp.java Add a comment that shows what the following Java code prints. You must take into account integer versus floating-point math, operator precedence, and parentheses. Your TA will show you a chart of operator precedence.
    // Operator precedence, integer math
    System.out.println(2 - 23 % 10 + 3 * 12 - 20);

    // Operator precedence, floating-point math
    System.out.println(2.4 + 23.1 - 10.0 * 3.1 - 12.5 / 6.25);
  
    // Operator precedence, mixed math
    System.out.println(65 % 15 + 3.5 * (5 / 2));
After completing the comments, copy the code into the main method in Exp.java and see how well you can interpret Java. Your TA will discuss the answers to the questions, before starting on the programming exercise below.

Using Scanners

Your TA will discuss the Scanner class:

Programming Exercise

Comment out the code that you copied from above, and add new code as shown below.

Java Variables

Following the instructions below, in order.
  1. Declare three variables of type int called A, B, and C, which represent the quadratic equation coefficients.
  2. Declare two variables of type double called positiveRoot and negativeRoot, to store the roots of the quadratic equation.
  3. Declare and instantiate an object of type Scanner to read from the keyboard, using a name of your choice.
  4. Prompt the user to input the A coefficient, using System.out.print, as follows: "Enter coefficient A: ".
  5. Read an integer from the keyboard into the variable A.
  6. Prompt the user to input the B coefficient, using System.out.print, as follows: "Enter coefficient B: ".
  7. Read an integer from the keyboard into the variable B.
  8. Prompt the user to input the C coefficient, using System.out.print, as follows: "Enter coefficient C: ".
  9. Read an integer from the keyboard into the variable C.
  10. Print the quadratic equation in the format shown in the sample output below.
  11. Look up the quadratic formula on the web.
  12. Compute the positive root and store it into the variable positiveRoot.
  13. Compute the negative root and store it into the variable negativeRoot.
  14. Print the positive root, with one digit after the decimal point, as shown below.
  15. Print the negative root, with one digit after the decimal point, as shown below.

Sample Output

Enter coefficient A: 1
Enter coefficient B: -11
Enter coefficient C: 24
Formula: 1x^2 + -11x + 24
Positive root: 8.0
Negative root: 3.0


Have your TA review your output for credit for this recitation


CS Banner
CS Building