Reputation: 95
When I provide my Java Command line arguments with this : Calculate 3 * 3
and when I print args.length
before making my operations, it returns 6 in the case of a multiplication.
Here is a screenshot of the results for java Calculate 3 * 3
Here is my code in two files:
Here is how to run it if Java is installed:
javac Calculate.java
java Calculate 3 * 3
Note: Whenever you try a multiplication for this program, args.length is 6. The program expects one numbers as operands and an operator ("+", "-", "*", "/" for addition, subtraction, multiplication and division respectively). That program works fine for all operations except multiplication.
Calculator.java
import java.util.Map;
import java.util.HashMap;
import java.util.function.BinaryOperator;
public final class Calculator {
// TODO: Fill this class in.
private final Map<String, BinaryOperator<Integer>> operators = new HashMap<>();
public void registerOperation(String symbol, BinaryOperator<Integer> operator){
operators.put(symbol.strip(), operator);
}
public int calculate(int a, String operator, int b){
return operators.get(operator).apply(a,b);
}
}
Calculate.java
public final class Calculate {
public static void main(String[] args) {
System.out.println(args.length);
System.out.println(args[2]);
if (args.length != 3) {
System.out.println("Usage: Calculate [int] [operator] [int]");
return;
}
Calculator calculator = new Calculator();
// TODO: Register the four "basic" binary operators: +, -, *, /
calculator.registerOperation("+", (a, b) -> a + b );
calculator.registerOperation("-", (a, b) -> a - b );
calculator.registerOperation("*", (a, b) -> a * b );
calculator.registerOperation("/", (a, b) -> a / b );
int a = Integer.parseInt(args[0]);
String operator = args[1];
int b = Integer.parseInt(args[2]);
System.out.println(calculator.calculate(a, operator, b));
}
}
Upvotes: 1
Views: 102
Reputation: 201429
The *
has a special meaning (all files in the current directory) to the command interpreter that starts java
. This happens for all programs. Quote the *
.
java Calculate 3 "*" 3
My advice would be to handle standard input (not arguments).
Upvotes: 4