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

2017/12/13

how to make random choice, but cannot choose same number

rey24 rey24

2017/12/13

#
there is my code, but null is cannot compatible to int
int a=Greenfoot.getRandomNumber(9)+1;
    int b=Greenfoot.getRandomNumber(9)+1;

    public void keluarSoal(int x,int y)
    {
        int ke;
        int jawabBenar = x+y;
        int jawabSalah = x+y+Greenfoot.getRandomNumber(3)-3;
        int [] pilihan = {jawabBenar, jawabSalah};
        for(int i =0; i <2; i++)
        {
            ke=Greenfoot.getRandomNumber(2);
            if(pilihan[ke]==null) //can't compile
                i--;
            else
            {
                Label jwb = new Label(pilihan[x],25);
                pilihan[x]=null;
            }
        }
danpost danpost

2017/12/13

#
What is line 13 supposed to be doing (what are you intending it to do)? The array is to contain elements of type 'int'. This is a primitive type which cannot be 'null' as all primitive types have default values ('false' for boolean and '0' for all others). So, if line 13 is trying to do what it looks like, then maybe you should check for a meaningless value, like '-1' and set it to that value at lines 18. Lines 18 and 19 seems to deal with a possible different element of the array (using index value from 'x' instead of 'ke'). In fact, it appears that if you use 'x', the index could end up out of bounds for the array. I believe you need to replace 'x' in those lines with 'ke'. I will presume that the discussion title is just a general description of what you are trying to do here. The first two lines of code, which declare two fields that are not used anywhere in the rest of the code, are unclear as to what they are doing there (unless they go with the title; but then the rest of the code would not seem to belong here). The 'for' loop appears to be creating two Label objects. Each of these objects are immediately lost at the end of the current iteration of the 'for' loop. In fact, the entirety of the code (starting from line 3) does absolutely nothing, as is.
You need to login to post a reply.