Я исправил его с помощью custom TextEntry. Изменен onSelectionChanged и поместил там код из loopj!
Мой код:
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
if (selStart >= 0) {
super.onSelectionChanged(selStart, selEnd);
} else {
setSelection(getText().length());
}
}
Вы можете использовать один экземпляр Random
Random rnd = new Random();
int count = 0,heads = 0;
while (heads < 3) {
int c1 = rnd.nextInt(2);
int c2 = rnd.nextInt(2);
int c3 = rnd.nextInt(2);
count++;
heads = c1+c2+c3;
System.out.println(count + "\t" +c1 +"\t" + c2 + "\t" +c3);
}
. Если вы хотите напечатать только конечный результат:
Random rnd = new Random();
int count = 0,heads = 0;
int c1 = 0, c2 = 0, c3 = 0;
while (heads < 3) {
c1 = rnd.nextInt(2);
c2 = rnd.nextInt(2);
c3 = rnd.nextInt(2);
count++;
heads = c1+c2+c3;
}
System.out.println(count + "\t" +c1 +"\t" + c2 + "\t" +c3);
//you can use only one rand obj to use Random()
Random rand = new Random();
//Initializing coins as 0
//Values of coins will change once we get random
int coin1 = 0;
int coin2 = 0;
int coin3 = 0;
//initializing heads and count as 0
int heads = 0;
int count = 0;
while(heads < 3){
//Assume '1' comes out for head and '0' for tail
coin1 = rand.nextInt(2);
coin2 = rand.nextInt(2);
coin3 = rand.nextInt(2);
//if all three coins are '1' which is head;
//sum should be 1+1+1 = 3
//while loop terminates because 3<3 is false
heads = coin1+coin2+coin3;
count++; //count = count +1;
}
//printing the value of count and coins
System.out.println(count + "\t" +coin1 + "\t" + coin2 + "\t" +coin3);
Вам не нужен if
. Ваши случайные значения: 0
или 1
. Предполагая, что значение 1
обозначает Head, вы можете посчитать количество головок, используя
heads = c1+c2+c3;
вместо if
.
Если вы предполагаете, что nextInt()
возвращает 1
, если головки были брошены, то присвойте сумму этих значений heads
.
heads = c1 + c2 + c3;
Существует также возможность использовать if
, если вы использовали nextBoolean()
вместо nextInt(2)
, который будет возвращать true
, если головки были брошены. Также изменяя переменные на boolean
вместо int
, код может выглядеть следующим образом:
while (heads < 3) {
boolean c1 = coin1.nextBoolean();
boolean c2 = coin2.nextBoolean();
boolean c3 = coin3.nextBoolean();
count++;
heads = 0;
heads += c1 ? 1 : 0; //incrementing heads if c1 is true
heads += c2 ? 1 : 0;
heads += c3 ? 1 : 0;
if(c1 && c2 && c3){ }
System.out.println(count + "\t" + c1 +"\t" + c2 + "\t" +c3);
}
Также в System.out.println(count + "\t" +coin1 +"\t" + coin2 + "\t" +coin3);
coin1
есть ссылка на объект Random
, что означает что-то вроде java.util.Random@74a14482
не ценность броска монеты. Если вы хотите напечатать 0
или 1
, вам нужно напечатать c1
. (то же самое с 2 и 3)