0

I study Java and I build a program with array:

com[0]="one";
com[1]="two";
com[2]="three";
[...]
com[9]="ten";

Every string of array is a commandment (my program is The 10 Commandment).

I'd like check if a commandment is already read. So, I think use a multidimensional array with string array and boolean array.

Is it possibile? What is the best way to do this?

thanks!

2
  • 4
    an array can't have two different types, have a look at hashmap Commented Dec 27, 2012 at 11:53
  • 1
    You can keep them separately in 2 arrays, same index referring to the same pair. Or you can define a new class and create an array of such object of that class. Commented Dec 27, 2012 at 11:53

3 Answers 3

3

There is no need for a multidimensional array here, this only adds complexity. You just need a class Commandment:

public class Commandment {

   private String commandment;
   private boolean read;

   public Commandment(String commandment) {
      this.commandment = commandment;
   }

   public void setRead(boolean read) {
      this.read = read;
   }

   public boolean isRead() {
      return this.read;
   }
}

Then you create an array of Commandments:

com[0]= new Commandment("one");
com[1]= new Commandment("two");
com[2]= new Commandment("three");

To change to 'read':

com[2].setRead(true);
Sign up to request clarification or add additional context in comments.

Comments

1

Have a separate array, same length and the indexes of that relate to those in your String array.

Probably a better way is to create an object like

public class Commandment {
    private String com;
    private String read;
    public (String com) {
        this.com = com;
        this.read = false;
    }
    public getCom() {
        return com;
    }
    public isRead() {
        return read;
    }
    public beenRead() {
        read = true;
    }
}

And make an array of those objects instead.

Commandment[] coms = new Commandment[10];
coms[0] = new Commandment("com1");
System.out.println(coms[0].getCom()+", has been read? "+coms[0].isRead());
coms[0].beenRead();
System.out.println(coms[0].getCom()+", has been read? "+coms[0].isRead());

Will create it, put in the first commandment as "com1" and then check if its been read, make it read, and check it again.

Comments

1

Or you can use two collections

String[] commandments="zero,one,two,three,four,five,six,seven,eight,nine,ten".split(",");
BitSet read = new BitSet(commandments.length);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.