Download File

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
AP Computer Science
Lab 10 a, b, c
Command Line Arguments, Exception Handling
Directions: These labs can go into a NEW project folder called Semester 2 (this folder is
separate from your Comp Sci Intro project folder). Save this new project folder under
your server folder (NOT the classroom folder).
Lab10a.java
Part 1: Summing integers
Write a program that passes an unspecified number of integers as one commandline argument and display their total. Use main (String [] args). At runtime, the
argument list on the command line will be “1 2 3 4 5” and the program will figure
out the total.
Example: java Lab8 “1 2 3 4 5”
The total is 15
Have all of this happen within a menu that the user can only exit if they select Q for
quit. (The menu can be short: P for new phrase and Q for quit.) You should use a
method to total the integers in the argument. You can decide if the method is void
or not.
You will need to tokenize the string (using a “ “ as the delimeter), and put each token
into a temporary string, tempStr. Then convert this tempStr to an integer. Google
“java string to integer” and look for the parseInt method. It returns an integer, and
has a String (use tempStr) in the argument list.
Do not worry about catching user errors yet, besides the menu options. We will
have error handling into the lab tomorrow.
Part 2: Exception Handling
Edit Part 1 of Lab 10a (parsing integers taken from the command line argument).
Create/include a try-catch block to trap the error that occurs if the string contains
non-integers. Print a Java-generated message if an error occurs. Find the sum of the
other integers in the input string.
Example:
Input: java Lab8 “1 2 3 4 5”
Output: A NumberFormatException occurred. Please enter a phrase that contains
numbers only next time. The total is 15.
Lab10b.java
Write a program that meets the following requirements:
1. Create an array with 50 randomly chosen integers, between 1 and 50.
2. Prompt the user for an array index value and display the contents of the array at that
index value. Assume that the end-user knows that arrays are indexed from 0, so an input of
0 to 49 would be valid.
3. Trap the error if the user specifies an index that is out of bounds, and print a Javagenerated error message. Re-prompt after the error.
Lab10c.java
Experiment with dividing by zero with integers and floats. Catch the exception for
divide-by-zero error with integers. Experiment with dividing by zero with doubles.