CS 140 - Lab 12 Instructions

Objectives

  1. Learn how to allow user input.
  2. Practice using Java's if-statement.
  3. Practice using Java's if-statement inside a for-loop.

Method

Part I - Getting input from the user

It would be nice to allow the user to enter data in a running Java program. The code below allows the user to enter a number from the interactions pane into a running Java program and then store the number in the variable x. Review the code below and then cut-and-paste this code into a main program and class Lab12.

  Scanner s = new Scanner(System.in);   // set up to read from the interactions pane
  System.out.print("Enter a number: "); // prompt for the first number 
  int x = s.nextInt();                  // read an integer
  1. Add a statement to print the value of x just to make sure the code above works. Compile and run it. Remember you'll have to click on the interactions tab in order to manually enter the number.
  2. What happens if you don't type an integer when prompted but something nonsensical such as the word hello?
  3. Add code to allow the user to enter two additional integers and place the values in variables y and z. Print the values to make sure it works.

Part II - Testing our values

  1. Add an if-statement to your code from part I that prints yes if x is between 0 and 100 inclusive, otherwise print no.
  2. Comment out of the if-statement you just wrote. Write another if-statement that prints negative is x is less than 0, zero if x is equal to zero, and positive if x is greater than 0.
  3. Write an if-statement that uses the logical operator && as well as the relational operators > and < to print out the largest of the three values. Example output might look like:
    Variable z contains the largest value
    
  4. Write a code segment that allows the user to enter ten integers and then counts the number of integers that are greater than 50. Print count at the end.

Extra Credit

Write a program that prompts the user for an integer x and then reads that many integers from the keyboard. Your program should find the largest integer entered and the final average of all the integers entered and print the results.


© Ed Harcourt