Отображение только уникальных элементов в массиве

1

Я создаю приложение викторины географии на андроид студии. Часть этого приложения викторины использует ImageView для отображения различных флагов. У меня проблемы с предотвращением повторного появления этого флага. Я хотел бы отображать флаги в случайном порядке, но также предотвращать их повторное появление. Как я могу это сделать?

Это мой класс, содержащий изображения:

package com.example.geonius;

public class containerfile {

public Integer [] Flags = {
        R.drawable.portugal,
        R.drawable.france,
        R.drawable.cuba,
        R.drawable.japan,
        R.drawable.southafrica,
        R.drawable.colombia,
        R.drawable.ethiopia,
        R.drawable.hungary,
        R.drawable.australia,
        R.drawable.cambodia,
        R.drawable.england,
        R.drawable.qatar,
        R.drawable.uae,
        R.drawable.kenya,
        R.drawable.india,
        R.drawable.china,
        R.drawable.nigeria,
        R.drawable.argentina,
        R.drawable.somalia,
        R.drawable.egypt,
        R.drawable.italy,
        R.drawable.usa
};

private String Choices [][] = {
        {"Portugal", "Spain", "Italy"},
        {"Netherlands", "France", "Germany"},
        {"Cuba", "Puerto Rico", "Panama"},
        {"Nepal", "Mongolia", "Japan"},
        {"Kenya", "Jamaica", "South Africa"},
        {"Venezuela", "Colombia", "Ecuador"},
        {"Ethiopia", "Eritrea", "Sudan"},
        {"Italy", "Hungary", "Lithuania"},
        {"New Zealand", "Fiji", "Australia"},
        {"Cambodia", "Vietnam", "Laos"},
        {"Iceland", "Finland", "England"},
        {"Qatar", "Argentina", "Bulgaria"},
        {"Bahrain", "Jordan", "UAE"},
        {"USA", "Kenya", "Sierra Leone"},
        {"Pakistan", "India", "Bangladesh"},
        {"China", "Russia", "Zimbabwe"},
        {"Nigeria", "Chile", "Czech Republic"},
        {"Bolivia", "Dominican Republic", "Argentina"},
        {"Somalia", "Djibouti", "Uganda"},
        {"Tunisia", "South Korea", "EGYPT"},
        {"Sweden", "Denmark", "Italy"},
        {"New zealand", "Slovakia", "United States of America"}

};

String CorrectChoice [] = {
  "Portugal",
  "France",
  "Cuba",
  "Japan",
  "South Africa",
  "Colombia",
  "Ethiopia",
  "Hungary",
  "Australia",
  "Cambodia",
  "England",
  "Qatar",
  "UAE",
  "Kenya",
  "India",
  "China",
  "Nigeria",
  "Argentina",
  "Somalia",
  "EGYPT",
  "Italy",
  "United States of America"

};

public Integer getFlags(int a) {
    Integer flags = Flags[a];
    return flags;
}

public String getOptions1(int a) {
    String options = Choices[a][0];
    return options;
}

public String getOptions2(int a) {
    String options = Choices[a][1];
    return options;
}

public String getOptions3(int a) {
    String options = Choices[a][2];
    return options;
}

public String getCorrectAnswers(int a) {
    String correctanswers = CorrectChoice[a];
    return correctanswers;
}

}

Это мой код Java под

 package com.example.geonius;

 import android.content.DialogInterface;
 import android.content.Intent;
 import android.support.v7.app.AlertDialog;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.ImageView;
 import android.widget.TextView;
 import java.util.Random;

public class Main3Activity extends AppCompatActivity {

Button answer1, answer2, answer3;
TextView score, Lives;
ImageView flag;

private containerfile Flags = new containerfile();

private String Answer;
private Integer GameScore = 0;
private Integer Life = 3;
private int flagsLength = Flags.Flags.length;

Random key;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main3);

    key = new Random();

    answer1 = (Button) findViewById(R.id.answer1);
    answer2 = (Button) findViewById(R.id.answer2);
    answer3 = (Button) findViewById(R.id.answer3);
    score = (TextView) findViewById(R.id.GameScore);
    Lives = (TextView) findViewById(R.id.life);
    flag = (ImageView) findViewById(R.id.flags);

    score.setText("Score: " + GameScore);
    Lives.setText("Lives: " + Life);


    updateQuestion(key.nextInt(flagsLength));

    answer1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (answer1.getText() == Answer) {
                GameScore++;
                score.setText("Score: " + GameScore);
                CorrectAnswer();
            }

            else if(Life == 0) {
                GameOver();
            }

            else if (answer1.getText() != Answer){
                Life--;
                Lives.setText("Lives: " + Life);
                NextQuestion();
            }
        }
    });

    answer2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (answer2.getText() == Answer) {
                GameScore++;
                score.setText("Score: " + GameScore);
                CorrectAnswer();
            }

            else if(Life == 0) {
                GameOver();
            }

            else if (answer2.getText() != Answer){
                Life--;
                Lives.setText("Lives: " + Life);
                NextQuestion();
            }
        }
    });

    answer3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (answer3.getText() == Answer) {
                GameScore++;
                score.setText("Score: " + GameScore);
                CorrectAnswer();
            }

            if(Life == 0) {
                GameOver();
            }

            else if (answer3.getText() != Answer) {
                Life--;
                Lives.setText("Lives: " + Life);
                NextQuestion();
            }
        }
    });
}

private void updateQuestion(int num) {
    flag.setImageResource(Flags.getFlags(num));
    answer1.setText(Flags.getOptions1(num));
    answer2.setText(Flags.getOptions2(num));
    answer3.setText(Flags.getOptions3(num));

    Answer = Flags.getCorrectAnswers(num);

}

private void GameOver() {
    AlertDialog.Builder alert = new           AlertDialog.Builder(Main3Activity.this);
    alert.setMessage("Game Over! You're score is " + GameScore).setCancelable(false).setPositiveButton("NEW GAME", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            startActivity(new Intent(getApplicationContext(), Main3Activity.class));
        }
    });

    alert.setNegativeButton("EXIT GAME", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });

    AlertDialog alertDialog = alert.create();
    alertDialog.show();
}

private void CorrectAnswer() {
    AlertDialog.Builder alert = new AlertDialog.Builder(Main3Activity.this);
    alert.setMessage("Correct!").setCancelable(false).setPositiveButton("Next Question", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            updateQuestion(key.nextInt(flagsLength));
        }
    });

    AlertDialog alertDialog = alert.create();
    alertDialog.show();
}

private void NextQuestion() {
    AlertDialog.Builder alert = new AlertDialog.Builder(Main3Activity.this);
    alert.setMessage("Incorrect Answer. The correct answer was " + Answer).setCancelable(false).setPositiveButton("Next Question", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            updateQuestion(key.nextInt(flagsLength));
        }
    });

    AlertDialog alertDialog = alert.create();
    alertDialog.show();
}
 }
Теги:
android-studio

1 ответ

0

Чтобы флаг не появлялся дважды подряд (если это действительно то, что вам нужно):

Где у вас есть

updateQuestion(key.nextInt(flagsLength));

Вы могли бы сделать следующее

1) при первом создании ключа сохраните его:

int currentKey = key.nextInt(flagsLength));

2) Затем, когда вы генерируете новый ключ для следующего вопроса:

int nextKey;
do {
    nextKey = key.nextInt(flagsLength));
} while nextKey == currentKey;
currentKey = nextKey;

3) Наконец, вы можете вызвать updateQuestion()

updateQuestion(currentKey);
  • 0
    Ваш код просто гарантирует, что два последующих вопроса не совпадают. Но все еще возможно, чтобы 1-й и 3-й вопросы были одинаковыми. Лучше создать коллекцию всех номеров вопросов List<Integer> allQurstionNumbers =....; а затем перемешать его с помощью Collections.shuffle

Ещё вопросы

Сообщество Overcoder
Наверх
Меню