0

My programming course wants me to have this kind of endcome:

  • Enter the first number!
  • 9
  • Enter the Second number!
  • 5
  • 9 + 5 = 14
  • 9 - 5 = 4
  • 9 * 5 = 45
  • 9 / 5 = 1.8 and this is the problem, the program I've written only gives me 1.0 as an answer. How can I get this number to be 1.8 not 1.0?

public class Nelilaskin {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);


        System.out.println("Enter the first number!");
        int first = Integer.valueOf(reader.nextLine());
        System.out.println("Enter the second number!");
        int second = Integer.valueOf(reader.nextLine());
        int plus = (first + second);
        int minus = (first - second);
        int multi = (first * second);
        double division = (first / second * 1.0);

        System.out.println(first + " + " + second + " = " + plus);
        System.out.println(first + " - " + second + " = " + minus);
        System.out.println(first + " * " + second + " = " + multi);
        System.out.println(first + " / " + second + " = " + division);


    }

}
pakkis26
  • 53
  • 2
  • See https://stackoverflow.com/a/14824454/2711811 – Andy Mar 16 '20 at 11:42
  • You're performing int division and then multiplying by `1.0`. You could cast `first` or `second` to a double, or you can change the type of the variable to double. – khelwood Mar 16 '20 at 11:42

2 Answers2

2

Consider replacing the data type for first and second as Float. And store the resultant in a float variable as well, then the output would be as required.

float plus = (first + second);
float minus = (first - second);
float multi = (first * second);
float division = first / second;
Sagar Dhawan
  • 37
  • 1
  • 7
  • 1
    Already tried this, but the course wants me to have the other answers as int values. If I change everything to float the outcome would be 14.0, 4.0, 45.0 and 1.8. – pakkis26 Mar 16 '20 at 11:47
  • 2
    Even if changing everything to `Float` is overkill _for now_, at least you know what to do if the next exercise is "Change your calculator to allow numbers with decimal points to be entered" (;->) – Kevin Anderson Mar 16 '20 at 11:53
1

this is because you are dividing two int values, try to cast at least one of them to double..

   double division = (double)first / (double)second ;
Bashir
  • 1,964
  • 5
  • 15
  • 34