I'm trying to learn java on my own. I am now re-doing some programs I've done before, but in a different way. Now I am stuck with a for-loop. I have the following code:
public class Head {
public static void main(String[] args) {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
for(int i=0; i<1000; i++){
int dice1 = 1 + (int)(Math.random() * ((6 - 1) + 1));
if (dice1 == 1){
a++;
}
else if(dice1 == 2){
b++;
}
else if(dice1 == 3){
c++;
}
else if(dice1 == 4){
d++;
}
else if(dice1 == 5){
e++;
}
else if(dice1 == 6){
f++;
}
}
System.out.println("Ones: " + a);
System.out.println("Twos: " + b);
System.out.println("Threes: " + c);
System.out.println("Fours: " + d);
System.out.println("Fives: " + e);
System.out.println("Sixes: " + f);
}
}
This works all fine and do what I want it to. Now I want to create a constructor with a method that do all the countings for me. So far so good. But when it comes to printing it out, the output returns everything the number of times it does the calculation. i.e, if I set i<5 it prints 1 2 3 4 5 6 five times, and not only one time.
Here is the bad code: public class Head { public static void main(String[] args) {
int a=0;
int b=0;
int c=0;
int d=0;
int e=0;
int f=0;
for(int i=0; i<5; i++){
int dice1 = 1 + (int)(Math.random() * ((6 - 1) + 1));
Dice diceObject = new Dice(dice1, a, b, c, d, e, f);
diceObject.CountNumbers();
// System.out.println(diceObject);
}
}
}
public class Dice {
private int a=0, b=0, c=0, d=0, e=0, f=0;
private int dice1;
public Dice(int dice1, int a, int b, int c, int d, int e, int f){
this.dice1 = dice1;
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
}
public int getDice1(){
return dice1;
}
public void CountNumbers(){
if (dice1 == 1){
a++;
}
else if(dice1 == 2){
b++;
}
else if(dice1 == 3){
c++;
}
else if(dice1 == 4){
d++;
}
else if(dice1 == 5){
e++;
}
else if(dice1 == 6){
f++;
}
}
}
Any help on this? Thank you very much for your time!