The first problem I see is you're casting Math.random() to int
and storing it as a double
.
double r = (int) (6 * Math.random()) +1;
This should look like this:
int r = (int) (6 * Math.random()) +1;
This results in 2 instead of 2.0. Doesn't really make a difference, but if you cast a double
value to int
you should store it as such. Otherwise, why cast it at all? You may also like to know about the Random
class. I think it looks a little cleaner:
int number = new Random().nextInt(6)+1;
Some would argue that Random
is more efficient than Math.random()
. See here.
Additionally, instead of if/else statements for this program I would recommend a switch statement like this:
switch (number) {
case 1:
System.out.println("Case 1");
break;
case 2:
System.out.println("Case 2");
break;
// so on, so forth
}
To sum it all up, try something like this:
import java.util.Random;
public class NewClass {
public static void main(String[] args) {
int number = 0;
while (number != 6) {
number = new Random().nextInt(6) + 1;
switch (number) {
case 1:
System.out.println("Case 1");
break;
case 2:
System.out.println("Case 2");
break;
case 3:
System.out.println("Case 3");
break;
case 4:
System.out.println("Case 4");
break;
case 5:
System.out.println("Case 5");
break;
case 6:
System.out.println("yay!");
break;
default:
System.out.println("default");
break;
}
}
}
}