-2

I have to write a program where the user inputs 3 numbers into an array and then the output is the numbers subtracted from each other.

I have tried using a for loop for this but it just outputs the numbers added together then turns it negative eg : if i put in the numbers 1,2 and 3 it should output -4 but outputs -6.

this is my code : (the print line part is in another method )

int sub = 0;

for(int j =0; j < numbers.length;j++)
{
    sub -= numbers[j];
}
return sub;

how do I get the numbers to subtract. Also if anyone knows how to get the numbers to divide by each other that would be really helpful : )

Thanks in advance

talex
  • 17,973
  • 3
  • 29
  • 66
EmilyP
  • 67
  • 4
  • 8
    0 - 1 - 2 - 3 == -6. Why would you expect it to be -4? (If you want to *start* with `numbers[0]` and subtract the other values from that, you need to change both your initialization of `sub` and your loop...) – Jon Skeet Aug 11 '15 at 17:05
  • 1
    What does "each other" mean when you talk about an array of 3 numbers? Please be more precise in your requirements. –  Aug 11 '15 at 17:09

3 Answers3

0
int sub = numbers[0];

for(int j = 1; j < numbers.length;j++)
{
    sub -= numbers[j];
}

return sub;

To divide, use /= instead of -=.

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
  • 1
    Note that if you just use /= for division, you'll get integer division, which is probably not what you want (you want floating point division) – yshavit Aug 11 '15 at 17:37
0

Change it to look like this:

int sub = numbers[0];

for (int j = 1; j < numbers.length; j++) {
    sub -= numbers[j];
}

return sub; 

Your code does

0 - numbers[0] - numbers[1] - numbers[2]

when what you want is

numbers[0] - numbers[1] - numbers[2]
Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102
0

It seems that you are assigning sub= 0 which is creating an issue. You need to assign the first value of array instead.

I have corrected the code for you:

    public static void main (String[] args) throws java.lang.Exception
    {

        int a [] ={1, 2, 3};
        int sub = a[0];
       for(int j =1; j < a.length;j++)
       {
        sub = sub -a[j];
       }
    System.out.println (sub);
    }

You may run this code here. You may find complete code here

Mahesh Kapoor
  • 244
  • 1
  • 4