Данный код работает:
package com.example.kurs;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
String[] word = {"Apple", "Carrot", "Orange", "Potato", "Sea"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Button b1;
Button b2;
Button b3;
public void onClick(View v){
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b3 = (Button) findViewById(R.id.b3);
int i = new Random().nextInt(5);
b1.setText(word[i]);
int g = new Random().nextInt(5);
while(g == i)
g = new Random().nextInt(5);
b2.setText(word[g]);
int r = new Random().nextInt(5);
while(r == i || r == g)
r = new Random().nextInt(5);
b3.setText(word[r]);
}
}
А данный нет:
package com.example.kurs;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
String[] word = {"Apple", "Carrot", "Orange", "Potato", "Sea"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
Button b3 = (Button) findViewById(R.id.b3);
public void onClick(View v){
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b3 = (Button) findViewById(R.id.b3);
int i = new Random().nextInt(5);
b1.setText(word[i]);
int g = new Random().nextInt(5);
while(g == i)
g = new Random().nextInt(5);
b2.setText(word[g]);
int r = new Random().nextInt(5);
while(r == i || r == g)
r = new Random().nextInt(5);
b3.setText(word[r]);
}
}
Хотелось бы узнать почему не робит, и желательно по простому)