I am trying to select a certain array out of 16 depending on what value is passed into the constructor of a class. The value entered will be used in a series of if statements that will choose the array. Something like this
package Model;
import javax.swing.*;
public class Die extends JButton{
String letters[] = new String[6];
public Die(int number){
Controller con = new Controller();
if(number==1){
for(int i = 0; i<5; i++}{
letters[i] = con.die1[i];
}
}
if(number==2){
for(int i = 0; i<5; i++}{
letters[i] = con.die2[i];
}
}
if(number==3){
for(int i = 0; i<5; i++}{
letters[i] = con.die3[i];
}
}
}
}
(Keep in mind that I haven't checked this code, and I have not created all 16 if statements).
Basically I want to compress these if statements somehow. Any ideas?
Declare a Map<Integer, String[]> that associates the number to the String to each die array and you would have not any conditional statements.
Controller con = new Controller();
Map<Integer, String[]> map = new HashMap<>();
map.put(1, con.die1);
map.put(2, con.die2);
map.put(3, con.die3);
if(number>=1 && number<=3){
for(int i = 0; i<5; i++}{
letters[i] = map.get(number)[i];
}
}
And as suggested by Lino you could even move this mapping into the Controller class which makes more sense in terms of responsibility :
private Map<Integer, String[]> map = new HashMap<>();
public Controller(){
map.put(1, die1);
map.put(2, die2);
map.put(3, die3);
}
public String getLetter(int number, int index){
map.get(number)[index];
}
And the Die client could be now :
Controller con = new Controller();
if(number>=1 && number<=3){
for(int i = 0; i<5; i++}{
letters[i] = con.getLetter(number, i);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With