How can you make a random not repeat it self? - java

I'v created a list of strings which I choose randomly to display, and so I want to make it that it won't repeat its self. How can I do that.
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final String randomQuestions = questions[new Random().nextInt(questions.length)];
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randomQuestions = questions[new Random().nextInt(questions.length)];
theQuestion.setText(randomQuestions);
}
});
}
The reason that I have two "randomQuestions" string is because I want a question to display as soon as you get into the activity and that on the click of a button it will randomise a new string.

Instead of everytime randomizing the pick, you can randomly shuffle the questions and sequentially take the next (random) question.
private final List<String> randomQuestions;
private int questionI;
// Cycling endlessly
private String nextQuestion() {
String question = randomQuestions.get(questionI);
++questionI;
if (questionI > randomQuestions.size()) {
questionI = 0;
}
}
// Once through the list:
private String nextQuestion() {
return randomQuestions.remove(0); // Always take the first, removing it.
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
randomQuestions = Collections.shuffle(Arrays.asList(questions));

Maybe you can create a list where you put the list of existing number like :
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
int a=new Random().nextInt(questions.length);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
ArrayList<Integer> existingNumber=new ArrayList<>();
final String randomQuestions = questions[a];
existingNumber.add(a);
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
do{
a=new Random().nextInt(questions.length);
}while(!existingNumber.add(a))
String randomQuestions = questions[a];
theQuestion.setText(randomQuestions);
}
});
}

public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final int index = new Random().nextInt(questions.length);
final String randomQuestions = questions[index];
questions[index] = questions[questions.length-1];
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randomQuestions = questions[new Random().nextInt(questions.length-1)];
theQuestion.setText(randomQuestions);
}
});
}

Use ArrayList to store your questions and after every retrieval of a question from a random index value, remove the same from ArrayList
Below is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
metadata = getIntent().getStringExtra("metadata");
final ArrayList<String> questions = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.questions)));
int i=new Random().nextInt(questions.size());
final String randomQuestions = questions.get(i);
questions.remove(i);
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(questions.size()==0) //To make sure we don't access the empty ArrayList
{
theQuestion.setText("End of questions");
return;
}
int i=new Random().nextInt(questions.size());
String randomQuestions =questions.get(i);
questions.remove(i);
theQuestion.setText(randomQuestions);
}
});
}

Related

How to set min/max lenght of Random Name created?

when I run this programm the emulator only gives me one letter when random name is generated by clicking a button.
I want to set the minimum generated lenghtname of chars in my string by 4 and maximum by 8. So the button generates a random Name by min 4 and max 8 letters from the String. Cant find any solution.
public class MainActivity extends AppCompatActivity {
private Switch Switch;
private EditText Name;
private Button btn;
private String items[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch = (Switch) findViewById(R.id.switch1);
Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
openActivity2();
}
});
Name = findViewById(R.id.editTextTextPersonName);
btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rndm = new Random();
int i = rndm.nextInt(items.length);
Name.setText(items [i]);
}
});
}
public void openActivity2() {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}
Thanks in advance.
You are using Name.setText(items[i]) which is only setting one character from items array to Name that's why you were getting one letter on clicking of button.
public class MainActivity extends AppCompatActivity {
private Switch Switch;
private EditText Name;
private Button btn;
private String items[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch = (Switch) findViewById(R.id.switch1);
Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
openActivity2();
}
});
Name = findViewById(R.id.editTextTextPersonName);
btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rndm = new Random();
String out = "";
// here length is will be a random number between 4 and 8
// this is used to get random number between 4(inclusive) and 9(exclusive)
int low = 4;
int high = 9;
int length = rndm.nextInt(high-low) + low;
for (int i=0;i<length;i++) {
int idx=rndm.nextInt(items.length);
out += items[idx];
}
Name.setText(out);
}
});
}
public void openActivity2() {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}

Can't change the value of integer variable

#RequiresApi(api = Build.VERSION_CODES.O)
public class MainActivity extends AppCompatActivity {
TextSwitcher textSwitcherage, textSwitcherGender;
Button nextButton, previousButton, nextButton2, previousButton2;
String[] age = {"U-4","Kid","Teen","Adult","Old"};
String[] gender = {"Male","Female","Other"};
TextView textView;
Typeface typeface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
defVars();
}
public void defVars()
{
textSwitcherGender = findViewById(R.id.textSwitcherGender);
textSwitcherage = findViewById(R.id.textSwitcherage);
nextButton = findViewById(R.id.nextButton1);
nextButton2 = findViewById(R.id.nextButton2);
previousButton = findViewById(R.id.previousButton1);
previousButton2 = findViewById(R.id.previousButton2);
typeface = getResources().getFont(R.font.lettersforlearners);
nextAndPreviousButtons(nextButton,previousButton,textSwitcherage,age,0);
nextAndPreviousButtons(nextButton2, previousButton2, textSwitcherGender, gender,0);
}
public void nextAndPreviousButtons(Button buttonNext, Button buttonPrevious, final TextSwitcher textSwitcher, final String[] data, final Integer stringIndex)
{
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(stringIndex == data.length - 1)
{
stringIndex = 0;
textSwitcher.setText(data[stringIndex]);
}
else
{
textSwitcher.setText(data[++stringIndex]);
}
}
});
buttonPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(stringIndex==0)
{
stringIndex = data.length-1;
textSwitcher.setText(data[stringIndex]);
}
else
{
textSwitcher.setText(data[--stringIndex]);
}
}
});
textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
textView = new TextView(MainActivity.this);
textView.setTypeface(typeface);
textView.setTextColor(Color.BLACK);
textView.setTextSize(40);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
return textView;
}
});
textSwitcher.setText(data[stringIndex]);
}
}
I have an error:
"error: cannot assign a value to final variable stringIndex"
I set the stringIndex final but still got that problem. I don't know. Am i have to define Integer variables for stringIndex? Or should I delete the stringIndex final? I need to define separate stringIndex variables for each function
if you declare final Integer stringIndex... then you are done! that is the idea and meaning of the reserved word final... is an object you cannot re assign after...
public void nextAndPreviousButtons(Button buttonNext, Button buttonPrevious,
final TextSwitcher textSwitcher, final String[] data, Integer stringIndex)
You don't have to modify stringIndex
public void nextAndPreviousButtons(Button buttonNext, Button buttonPrevious, final TextSwitcher textSwitcher, final String[] data, final Integer stringIndex)
{
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(stringIndex == data.length - 1)
{
textSwitcher.setText(data[0]);
}
else
{
textSwitcher.setText(data[stringIndex+1]);
}
}
});
buttonPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(stringIndex==0)
{
textSwitcher.setText(data[data.length-1]);
}
else
{
textSwitcher.setText(data[stringIndex-1]);
}
}
});
textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
textView = new TextView(MainActivity.this);
textView.setTypeface(typeface);
textView.setTextColor(Color.BLACK);
textView.setTextSize(40);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
return textView;
}
});
textSwitcher.setText(data[stringIndex]);

I want to let the data to be shown on the edittext

I want to let the data to be shown on the edittext first. How can I do it? I've already passed the data to the modify page, and I want to let the data first show on the edittext, then let the user change the title if the user needs to change.
Here are my modify page code:
public class MeTodolistModify extends AppCompatActivity implements View.OnClickListener {
private String student_id,student_name,title,input;
private EditText addtext;
private Button change;
private int position;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_me_todolist_modify);
Bundle bundle = getIntent().getExtras();
title = bundle.getString("title");
position = bundle.getInt("position");
student_id = bundle.getString("student_id");
student_name = bundle.getString("student_name");
createDetail();
}
private void createDetail(){
final FirebaseDatabase db = FirebaseDatabase.getInstance();
final DatabaseReference ref = db.getReference("Student").child(student_id).child("event");
Log.e("MOD",String.valueOf(position));
Log.e("MOD2",title);
change = findViewById(R.id.change);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText addtext = findViewById(R.id.addtext);
input = addtext.getText().toString();
ref.child(Integer.toString(position)).setValue(input);
Intent intent;
switch (v.getId()) {
case R.id.change:
intent = new Intent(MeTodolistModify.this, MeTodolist.class);
intent.putExtra("student_id", student_id );
intent.putExtra("student_name",student_name);
startActivity(intent);
break;
}
}
});
}
#Override
public void onClick(View v) {
}
}
The update code for modify page:
public class MeTodolistModify extends AppCompatActivity implements View.OnClickListener {
private String student_id,student_name,title,input;
private EditText addtext;
private Button change;
private int position;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_me_todolist_modify);
Bundle bundle = getIntent().getExtras();
title = bundle.getString("title");
position = bundle.getInt("position");
student_id = bundle.getString("student_id");
student_name = bundle.getString("student_name");
createDetail();
}
private void createDetail(){
final FirebaseDatabase db = FirebaseDatabase.getInstance();
final DatabaseReference ref = db.getReference("Student").child(student_id).child("event");
Log.e("MOD",String.valueOf(position));
Log.e("MOD2",title);
change = findViewById(R.id.change);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText addtext = findViewById(R.id.addtext);
addtext.setText(title);
input = addtext.getText().toString();
ref.child(Integer.toString(position)).setValue(input);
Intent intent;
switch (v.getId()) {
case R.id.change:
intent = new Intent(MeTodolistModify.this, MeTodolist.class);
intent.putExtra("student_id", student_id );
intent.putExtra("student_name",student_name);
startActivity(intent);
break;
}
}
});
}
#Override
public void onClick(View v) {
}
}
after getting title from bundle
title = bundle.getString("title");
set title to EditText
addtext.setText(title)
later user can change if he wants
If you want to programmatically set data to EditText
addtext.setText("Some text");

unable to match edittext with image name

Learning android by making a simple guessing game, I have set the images in an Arraylist and applied random operation on it, but now I'm confused how to match edit text value with image name so that I can set score.
public class MainActivity extends AppCompatActivity {
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Integer> list = new ArrayList<Integer>();
ImageView random_image = (ImageView) findViewById(R.id.imageView);
final int[] images = {R.drawable.kung_fu_panda, R.drawable.mr_nobody, R.drawable.toy_story};
list.add(R.drawable.kung_fu_panda);
list.add(R.drawable.mr_nobody);
list.add(R.drawable.toy_story);
int position = new Random().nextInt(list.size());
random_image.setImageResource((Integer) list.get(position));
list.remove(position);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
private void validateInput() {
String input = editText.getText().toString();
}
You can try definition name's array of images, and get the name by random position, and use currentName save the name.
String currentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Integer> list = new ArrayList<Integer>();
ImageView random_image = (ImageView) findViewById(R.id.imageView);
final String imageNames = {"kung fu panda", "mr nobody", "toy story"};
list.add(R.drawable.kung_fu_panda);
list.add(R.drawable.mr_nobody);
list.add(R.drawable.toy_story);
int position = new Random().nextInt(list.size());
random_image.setImageResource((Integer) list.get(position));
currentName = imageNames[position];
list.remove(position);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
Then, in your validateInput() method, you can use currentName to compare, notice case, use String.toLowerCase() to format input string.
private boolean validateInput() {
String input = editText.getText().toString();
if(!TextUtils.isEmpty(input)){
input = input..toLowerCase();
if(input.equeals(currentName)){
return true;
}
}
return false;
}

How to make my app loads the articles from the beginning?

I have a simple app with 50 articles, my previous and next button work good in all choices BUT when the user goes to the end (at 50th article) the app can't load again from the beginning the 1st article.
Thanks for any help, here is my code:
I don't know if needs more cede for to be clear, cause I am a newbie.
public class StoryActivity extends AppCompatActivity {
public static final String TAG = StoryActivity.class.getSimpleName();
private Story mStory = new Story();
private ImageView mImageView;
private TextView mTextView;
private Page mCurrentPage;
private String mName;
private Button mPreviousButton;
private Button mNextButton;
private ScrollView mScrollView;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story2);
//Intent intent = getIntent();
//mName = intent.getStringExtra(getString(R.string.key_name));
if(mName == null){
mName = "";
}
Log.d(TAG, mName);
mImageView = (ImageView)findViewById(R.id.storyImageView);
mTextView = (TextView)findViewById(R.id.storyTextView);
mPreviousButton = (Button)findViewById(R.id.previousButton);
mNextButton = (Button)findViewById(R.id.nextButton);
mTextView.setMovementMethod(new ScrollingMovementMethod());
loadPage(0);
}
private void loadPage(int choice){
mCurrentPage = mStory.getPage(choice);
Drawable drawable = getResources().getDrawable(mCurrentPage.getImageId());
mImageView.setImageDrawable(drawable);
String pageText = mCurrentPage.getText();
//add the name if placeholder included.
//pageText = String.format(pageText,mName);
mTextView.setText(pageText);
if(mCurrentPage.isSingle()){
mPreviousButton.setVisibility(View.VISIBLE);
mNextButton.setText("");
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadPage(0);
}
});
}else{
mPreviousButton.setText(mCurrentPage.getChoices().getText1());
mNextButton.setText(mCurrentPage.getChoices().getText2());
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int previousPage = mCurrentPage.getChoices().getPreviousPage();
loadPage(previousPage);
}
});
mNextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int nextPage = mCurrentPage.getChoices().getNextPage();
loadPage(nextPage);
}
});
}}
}

Categories

Resources