Writing Calculator class into a "Command Line Calculator" program (Java) -
here relevant part of main program assignment:
public static void main(string [] args) { int characters = args.length; if (characters < 3) system.out.println("you did not type in calculation!"); else if (characters % 2 == 0) system.out.println("invalid number of command line parameters."); else { calculathor counter = new calculathor(); counter.count(args); } } }
i'm allowed write class shown below (calculator) program in assignment. can't figure out how printable result calculation.
i presume switch statement working intended in receiving operator user's input , putting use need else actual result.
class calculator { int result; int = 0; string[] args; void count(string[] args) { switch (args[i].charat(i)) { case '+': result = integer.parseint(args[i]) + integer.parseint(args[i+2]); break; case '-': result = integer.parseint(args[i]) - integer.parseint(args[i+2]); break; } system.out.println("\nresult of calculation " + args[0] + " + " + args[2] + " + " + args[4] + " - " + args[6] + " " + result); } }
here pointers:
calculathor counter = new calculathor();
should be
calculator counter = new calculator();
and, switch statement more or less substitute if-elseif-else-statements (see linked tutorial clarification).
you want loop on each argument , check if it's number or operator. example:
for(string arg: args){ ///code }
or
for(int = 0; < args.length; i++) { //code }
within loop can have switch statement checks if current arg int or operator. could, example, increment i
more 1 one summation @ each iteration, e.g i+=3
instead of i++
(warning: think through don't arrayindexoutofboundsexception
)
also, there's no need charat
since each arg string of length 1 (i assume). if have 1 big string want loop on args[0]
.
Comments
Post a Comment