0

I want my variable i to have the value of these fractions depending on a random number. However, when I print out i, it displays 1.0. Why is that and how can I solve this issue?

public class Musik{
  public static void main(String[] args){
    Interval();
    System.out.println(Interval());
  }
  public static double Interval(){
    int a = (int)(Math.random() * 5);
    System.out.println(a);
    double i = 0;
    switch (a) {
      case 0 : 
        i = 2;
        break;
      case 1 : 
        i = 3/2;
        break;
      case 2 : 
        i = 4/3;
        break;
      case 3 : 
        i = 5/4;
        break;
      case 4 : 
        i = 9/8;
        break;        
    }
    return i;    
  }
}
alex.zxg
  • 11
  • 3
  • *Integer division* effect: when we divide `int` to `int` (say `9` to `8`) the result will be `int` as well (`1`); put it as `9.0 / 8.0` (please, note `.0`) – Dmitry Bychenko Dec 25 '19 at 15:00

2 Answers2

2

Because 3/2 is a division between two integers with the outcome of 1. You probably want to divide the two doubles 3.0/2.0 with the outcome of 1.5

Shloim
  • 5,281
  • 21
  • 36
1

If you are expecting result with decimal precision, add d to your denominator

Ex:

5/3 returns 1

But

5/3d returns 1.6666666666666667

Sunil Dabburi
  • 1,442
  • 12
  • 18