CS160: Foundations in Programming
Command-line arguments & methods
The purpose of this lab is to gain experience in working with command-line
arguments and strings and methods.
New Instructions
This lab should seem quite familiar.
It's a lot like a previous lab, except that you need to write some methods:
- a method get_number to turn a string into a double.
- a method operator_plus to perform addition.
- a method operator_minus to perform subtraction.
- et cetera
What arguments should these methods take?
What type should these methods return?
Work that out before you start writing code.
Old Instructions
You are to write a very simple calculator. It will take,
as command-line arguments, either:
- one argument: a single number
- three arguments: a number, an operator, and another number
If the program gets a single number, it should print it.
If the program gets a number, an operator, and another number,
it should do the math, and print the result.
The operators can be +, -, *, and /.
Also, instead of a number, the program must recognize
the special constants
pi
and avo.
Sample runs
In the following sample runs, > is your prompt.
What you type looks like this.
> java calc 42
42.0
> java calc 1.234
1.234
> java calc pi
3.141592653589793
> java calc avo
6.02214179E23
> java calc 2 + 2
4.0
> java calc pi + 10
13.141592653589793
> java calc avo / 2
3.011070895E23
> java calc 1 + 2 + 3
Bad arguments
For extra fame & glory
- Handle invalid numbers such as xyz or 3X.
- Handle octal numbers, beginning with a 0.
- Handle hexadecimal numbers, beginning with 0x.
- Handle division by zero.
- Handle more than three arguments.
Submit the printout of your program
to your GTA to get credit for this lab.
© 2009 CSU