编程遇到问题啦!
题目在这里:
1.1 Learning objectives
Using String methods
Using the matches method and regular expression
Using exception
1.2 Task
Write a program Calculator.java to implement a simple calculator of basic operations (addition, subtraction, multiplication and division) on integers.
The user may enter a string comprising an operand, a binary operator, and a second operand, with any number of space characters between them. There may be leading spaces and trailing spaces in the input.
If an invalid input is encountered, a message "Error in expression" is displayed and the calculation is skipped. Otherwise, the respective operation is carried out, and the result displayed. The user then enters another string. To end the calculation, the user enters 'q' (without any leading or trailing spaces).
The operand is an integer. Examples of valid operands are 23, 0, -123, but not 23.5 (not an integer), 51.0 (not an integer), +123 (unary plus not accepted). You may assume that the operands and the result are within the range of value of the int type.
You need to handle division-by-zero error so that your program does not crash when it happens.
A partial code is given:
import java.util.*;
class Calculator {
Scanner scanner = new Scanner(System.in);
//-----------------------------------------------------
// Data members
//-----------------------------------------------------
String expr;
int length;
int index;
//-----------------------------------------------------
// Constructor
//-----------------------------------------------------
public Calculator () {
}
//-----------------------------------------------------
// main method
//-----------------------------------------------------
public static void main (String [] args) {
Calculator cal = new Calculator();
// to be filled in
}
// You may add other methods here
}
The data members given in the partial code are just suggestions. You are free to use your own approach.
Please refer to the sample outputs below.
1.3 Sample runs
Sample run using interactive input:
$ javac Calculator.java
$ java Calculator
123 + 345
123 + 345 = 468
-20+13
-20 + 13 = -7
004 -10
4 - 10 = -6
12*-0011
12 * -11 = -132
30 / 4
30 / 4 = 7
123/-7
123 / -7 = -17
q
Another sample run that shows some invalid inputs:
$ java Calculator
xyz
Error in expression
a + b
Error in expression
12345
Error in expression
-10 *
Error in expression
12.3 + 32
Error in expression
1 + 2 + 3
Error in expression
+30 / 3
Error in expression
30 // 7
Error in expression
333 / 0
Division by zero error
333 / 4
333 / 4 = 83
q
1.4 Important notes
Ensure that the outputs of your program comform to the format of the sample outputs given.
很急啊!小女子先在这里谢谢各位了!