-4

I want to make a simple calculator but, I don't know how to enter many operations just like a real calculator.

switch (choice)
        {
            case 1:
                System.out.println("Please enter 2 numbers only: " );
                x = input.nextInt();
                y = input.nextInt();
                sum = calc.add(x,y);
                System.out.printf("The sum is %d\n\n",sum);
                out.write(x + "+" + y + "=" + sum);
                break;       
            case 2:
              ...
            case 3:
            ...
        }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Sum only refers to addition. Multiplied numbers are a product; divided numbers are a quotient; subtracted numbers are a difference. – Anthony May 04 '12 at 11:32
  • Also, you repeat the same first 3 lines in each case. You could probably move that out to a function or just initial prompt and then have the case be based on which operation they choose. Oh, and Modulo I think would be remainder and exponents are weird and can be called products or powers. – Anthony May 04 '12 at 11:38
  • I took the liberty to remove the exact repetitions in the code. It added zero information and forced everyone to find out for himself that it's just copypasta. – Marko Topolnik May 04 '12 at 11:47

2 Answers2

2

There is no question but I have some suggestions.

I would

  • make the case statements based on the operation '+', instead of 1.
  • make the messages match the operations. e.g. write(x + "*" + y when multiplying. Also don't call them all "sum"
  • make sure I read the nextLine() at the end.
  • write a new line after each line.
  • add a default: when the user enters an unknown operation.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Use the ScriptEngine. E.G. here.

=

That has a GUI (obviously) but you could simply allow the user to type in whatever formula JS can handle. Here is another example at my site that allows formula entry by text field.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433