# Thread: How do I compute all the possible arithmetic operations of 4 integers?

1. Member Join Date
Nov 2014
Posts
1
Rep Power
0

## How do I compute all the possible arithmetic operations of 4 integers?

Hey guys, I'm new to Java and I want to write a program that compute all the possible arithmetic operations of 4 integers.
For example, if the user enter 1, 2, 3, and 4 respectively, then I want the computer to print out the following results:
1 + 2 + 3 + 4
1 + 2 + 3 - 4
1 + 2 + 3 * 4
1 + 2 + 3 / 4
...
1 / 2 / 3 / 4

(parenthesis can be ignored for this program)

This is what I have so far, but I don't know how to continue:
import java.util.Scanner;

public class ArithmeticComputation{
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int num1 = stdin.nextInt();
int num2 = stdin.nextInt();
int num3 = stdin.nextInt();
int num4 = stdin.nextInt();
char[] operation = { '+', '-', '*', '/' };
for (int i = 0; i < operation.length; i++) {
for (int j = 0; j < operation.length; j++) {
for (int k = 0; k < operation.length; k++) {

I'm looking for a method that allows me to assign char into actual operators, so that I can loop through all the computation.
I'd really appreciate it if anyone can help me out!  Reply With Quote

2. ## Re: How do I compute all the possible arithmetic operations of 4 integers?

For the first pass on finding a solution, just generate Strings for all the expressions and print them out.

When that works, look at creating an expression evaluator that will parse the String and evaluate it.
Last edited by Norm; 11-25-2014 at 10:14 PM.  Reply With Quote

3. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## Re: How do I compute all the possible arithmetic operations of 4 integers?

And in some cases, you will need to change the order of the numbers (e.g. 2/3 != 3/2). So generating permutations would be helpful.

Regards,
Jim  Reply With Quote

4. ## Re: How do I compute all the possible arithmetic operations of 4 integers?

Do you want to allow parentheses as well? e.g. (1+2)*(3+4)

kind regards,

Jos

edit: duh, I missed your remark about those parentheses; an easy solution would be to transform your expressions to postfix form (they don't need parentheses and you can evaluate a b op1 c op2 d op3)
Last edited by JosAH; 11-26-2014 at 10:38 AM.  Reply With Quote

arithmetic, char, computation, loop, operators 