This site requires JavaScript, please enable it in your browser!
Greenfoot back
Astralman
Astralman wrote ...

2018/5/13

How do I reference an array?

Astralman Astralman

2018/5/13

#
Not sure if "reference" is the right word. Let me explain. If I made a method that randomly flips a quarter (heads or tails), then made this
public Coin(){
       toss();
    }
	
Then I created an object - something like this:
public static void main (String[] args){
Coin quarter= new Coin();
} 
I know I could just say quarter.toss(); and it flips the quarter. But what if I made an array?
String coinName[] = {"quarter"};
OR
double coin [] = new double [1];
coin [0] = 0.25;
How can I reference the number of the array with the toss constructor, like how I did with quarter.toss()? I was trying indexOf but it's not working. I hope that makes sense.
danpost danpost

2018/5/13

#
What is your toss method? I really do not see any place where there are two options (one for heads and one for tails).
Astralman Astralman

2018/5/13

#
Oh, I didn't think it was important. I thought it was simple question.
public class Coin{

	private String sideUp;

    public void toss(){

        Random random = new Random();

        int randomNumber;

        randomNumber = random.nextInt(2);
        if (randomNumber == 1){
            sideUp = "tails";
        }
        else{
            sideUp = "heads";
        }
	}

    public String getSideUp(){
        return sideUp;
	}

    public Coin(){
       toss();
    }
danpost danpost

2018/5/13

#
Astralman wrote...
Oh, I didn't think it was important. I thought it was simple question. << Code Omitted >>
It was needed for context. Did you try something like:
Coin[] coins;
for an array? If you wanted each coin to have a denomination, it should probably be held by the Coin objects themselves in a String or a float field (with another "getter" method for its value).
Astralman Astralman

2018/5/13

#
I tried this:
Coin coinName [] = new Coin[1];
	coinName [0] = "quarter";
Is this okay? But how I get it to reference with toss()?
Astralman Astralman

2018/5/13

#
Is a getter, like an accessor? But wouldn't that be different from an array? Or can I put the array inside getter?
danpost danpost

2018/5/13

#
Astralman wrote...
Is a getter, like an accessor? But wouldn't that be different from an array? Or can I put the array inside getter?
The getSideUp method in the Coin class is an example of a "getter" method. I was suggesting a similar method to return the type of coin, which would be held in another field (similar to line 3 in the Coin class given above). The array, on the other hand will be far removed from it -- in a different class altogether.
Astralman Astralman

2018/5/15

#
Got it. Thanks!
You need to login to post a reply.