1

I am new to Java and am trying to make a program run to solve and display the output of the equations. I have tried changing the places of the parenthesis, and putting equations in other parts of the code but I either get 0 as the output or wrong answers. Any words of wisdom would be greatly appreciated.

import java.util.*;
import static java.lang.Math.*;

public class JFirstTest
{
   public static void main(String[] args)
   {
    // Declare variables and equations

    int W, X, Y, Z;

    W = 10;
    X = 20;
    Y = 30;
    Z = 40;

    int FormulaOne   = (W + X) / (Y + Z);
    int FormulaTwo   = (X + ( Y / W)) / Z;
    int FormulaThree = X * (W - Y)/ (X * Y - Z);


    // System.out.println formulas

    System.out.println("\n\tWhen W=" + W + "  X=" + X + " Y=" + Y + " Z=" +    Z + " then FormulaOne =    " + FormulaOne);
    System.out.println("\n\tWhen W=" + W + "  X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaTwo =    " + FormulaTwo);
    System.out.println("\n\tWhen W=" + W + "  X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaThree =  " + FormulaThree);


    System.out.println("\n");

Update: This has been marked as Duplicate, however, I did searches before I
posted this question and the answers eluded me...Also changed int to double 
and now it works fine.
  • 6
    Should be double and not int. Case closed. – Shahar Feb 11 '15 at 18:09
  • 1
    Semantically, `(X + ( Y / W)) / Z` (where X, Y and Z are ints) is like `int r1 = Y / W; int r2 = X + r1; int r3 = r2 / Z;` - why might that be a problem? Inspect each intermediate variable (which is an expression in the original) and compare with the expected value. – user2864740 Feb 11 '15 at 18:14
  • Learn and follow the Java coding standards. You're using C# style variable names. https://google-styleguide.googlecode.com/svn/trunk/javaguide.html – duffymo Feb 11 '15 at 18:42
  • Thank you for the info, and I will definately look up those Java coding standards. – N. M. Greasby Feb 11 '15 at 19:02
  • @duffymo: Locals are camelCase in C#, too. – Joey Feb 19 '15 at 09:33
  • They don't start with capital letters; those are for classes. – duffymo Feb 19 '15 at 10:08

2 Answers2

2

Dividing integer by integer will result in integer, and round down (truncate). So, dividing smaller number by larger will result in zero, so you may want to consider changing type of variables to float / double.

2

Think of it this way... if an int (integer) is a whole number, then if you divide, for example, 10 by 20, then your program is just going to give you back 0 because 0.5 is not an integer (so it rounds down).

What primitive data type would you use to account for any decimals?

Answer: Double

freddiev4
  • 2,501
  • 2
  • 26
  • 46