Android 重复随机数

Android 重复随机数,android,Android,我正在创建一个android项目,一个测验应用程序 当我尝试随机复制id时,我不知道如何修复它 我需要我的程序生成一个没有任何重复的随机数 她是我的代码活动 package com.example.testing; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.Timer; import j

我正在创建一个android项目,一个测验应用程序

当我尝试随机复制id时,我不知道如何修复它
我需要我的程序生成一个没有任何重复的随机数

她是我的代码活动

    package com.example.testing;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class QuestionActivity extends Activity{

    ArrayList<Question> quesList;
    int score = 0;
    int qid = 0;
    int lives = 5;




    Question currentQ;
    TextView txtQuestion, times, scored, livess;
    Button button1, button2, button3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        QuizHelper db = new QuizHelper(this);  // my question bank class
        quesList = db.getAllQuestions();
        Random random = new Random();// this will fetch all quetonall questions
        currentQ = quesList.get( random.nextInt(quesList.size())); // the current question
        txtQuestion = (TextView) findViewById(R.id.txtQuestion);
        // the textview in which the question will be displayed
        // the three buttons,
        // the idea is to set the text of three buttons with the options from question bank
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);

        livess = (TextView) findViewById(R.id.livess);
        // the textview in which  will be displayed
        scored = (TextView) findViewById(R.id.score);
        // the timer
        times = (TextView) findViewById(R.id.timers);
        // method which will set the things up for our game
        setQuestionView();
        times.setText("00:02:00");
        // A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
        CounterClass timer = new CounterClass(60000, 1000);
        timer.start();
        // button click listeners
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // passing the button text to other method
                // to check whether the anser is correct or not
                // same for all three buttons
                getAnswer(button1.getText().toString());
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button2.getText().toString());
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button3.getText().toString());
            }
        });
    }
    public void getAnswer(String AnswerString) {
        if (currentQ.getANSWER().equals(AnswerString)) {
            // if conditions matches increase the int (score) by 1
            // and set the text of the score view
            score++;
            scored.setText("Score : " + score);




        } else if(lives > 1){
            lives--;
            livess.setText("Lives: " + lives);


        }

        else {
            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();

        }

        {


        }
        if (qid < 20) {
            // if questions are not over then do this
            Random random = new Random();
            currentQ = quesList.get( random.nextInt(quesList.size()));
            setQuestionView();
        } else {
            // if over do this
            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();
        }
    }
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    public class CounterClass extends CountDownTimer {
        public CounterClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }
        @Override
        public void onFinish() {
            times.setText("Time is up");
            Intent intent = new Intent(QuestionActivity.this,
                    Result_Activity_TimesUp.class);
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();
        }
        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            long millis = millisUntilFinished;
            String hms = String.format(
                    "%02d:%02d:%02d",
                    TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
                            .toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis)
                            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
                            .toMinutes(millis)));
            System.out.println(hms);
            times.setText(hms);
        }
    }
    private void setQuestionView() {
        // the method which will put all things together
        txtQuestion.setText(currentQ.getQUESTION());
        button1.setText(currentQ.getOPTA());
        button2.setText(currentQ.getOPTB());
        button3.setText(currentQ.getOPTC());
        qid++;


    }


}
package com.example.testing;
导入java.util.ArrayList;
导入java.util.Collection;
导入java.util.List;
导入java.util.Random;
导入java.util.Timer;
导入java.util.concurrent.TimeUnit;
导入android.annotation.SuppressLint;
导入android.annotation.TargetApi;
导入android.app.Activity;
导入android.content.Intent;
导入android.graphics.Typeface;
导入android.media.MediaPlayer;
导入android.os.Build;
导入android.os.Bundle;
导入android.os.CountDownTimer;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.TextView;
公共类活动扩展了活动{
ArrayList quesList;
智力得分=0;
int-qid=0;
int=5;
问题Q;
TextView txtQuestion、时间、得分、livess;
按钮1、按钮2、按钮3;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuizHelper db=newquizhelper(this);//我的问题库类
quesList=db.getAllQuestions();
Random Random=new Random();//这将获取所有问题所有问题
currentQ=quesList.get(random.nextInt(quesList.size());//当前问题
txtQuestion=(TextView)findViewById(R.id.txtQuestion);
//显示问题的文本视图
//三个按钮,
//这个想法是用题库中的选项设置三个按钮的文本
button1=(按钮)findViewById(R.id.button1);
button2=(按钮)findViewById(R.id.button2);
button3=(按钮)findViewById(R.id.button3);
livess=(TextView)findViewById(R.id.livess);
//将在其中显示的文本视图
得分=(TextView)findViewById(R.id.score);
//计时器
times=(TextView)findViewById(R.id.timers);
//为我们的游戏做准备的方法
setQuestionView();
times.setText(“00:02:00”);
//播放时间为60秒的计时器,间隔为1秒(1000毫秒)
反课堂计时器=新的反课堂(60000,1000);
timer.start();
//按钮单击侦听器
button1.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//将按钮文本传递给其他方法
//以检查anser是否正确
//所有三个按钮都相同
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
getAnswer(按钮3.getText().toString());
}
});
}
public void getAnswer(字符串AnswerString){
if(currentQ.getANSWER().equals(AnswerString)){
//如果条件匹配,则将整数(分数)增加1
//并设置分数视图的文本
分数++;
scored.setText(“分数:+分数”);
}else if(生命>1){
生命--;
setText(“生活:+生活”);
}
否则{
意向意向=新意向(QuestionActivity.this,
结果类);
Bundle b=新Bundle();
b、 putInt(“分数”,分数);//你的分数
意图。额外加分(b);//把你的分数记到下一个分数上
星触觉(意向);
完成();
}
{
}
如果(qid<20){
//如果问题还没有结束,那么就这样做
随机=新随机();
currentQ=quesList.get(random.nextInt(quesList.size());
setQuestionView();
}否则{
//如果过了头,就这样做
意向意向=新意向(QuestionActivity.this,
结果类);
Bundle b=新Bundle();
b、 putInt(“分数”,分数);//你的分数
意图。额外加分(b);//把你的分数记到下一个分数上
星触觉(意向);
完成();
}
}
@TargetApi(构建版本代码姜饼)
@SuppressLint(“新API”)
公共类反类扩展倒计时{
公共反汇编(长百万未来,长倒计时间隔){
超级(毫秒未来,倒计时间隔);
//TODO自动生成的构造函数存根
}
@凌驾
公共无效onFinish(){
times.setText(“时间到了”);
意向意向=新意向(QuestionActivity.this,
结果(活动)(时间上限.类);;
Bundle b=新Bundle();
b、 putInt(“分数”,分数);//你的分数
意图。额外加分(b);//把你的分数记到下一个分数上
星触觉(意向);
完成();
}
@凌驾
公共void onTick(长毫秒未完成){
//TODO自动生成的方法存根
长密耳=完成的密耳;
String hms=String.format(
“%02d:%02d:%02d”,
时间单位。毫秒。至小时(毫秒),
时间单位.毫秒.t分钟(毫秒)
-TimeUnit.HOURS.toMinutes(TimeUnit.ms
.To小时(毫秒)),
TimeUnit.millizes.to
package com.example.testing;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class QuizHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 3;
    // Database Name
    private static final String DATABASE_NAME = "mathsone";
    // tasks table name
    private static final String TABLE_QUEST = "quest";
    // tasks Table Columns names
    private static final String KEY_ID = "qid";
    private static final String KEY_QUES = "question";
    private static final String KEY_ANSWER = "answer"; // correct option
    private static final String KEY_OPTA = "opta"; // option a
    private static final String KEY_OPTB = "optb"; // option b
    private static final String KEY_OPTC = "optc"; // option c
    private SQLiteDatabase dbase;
    public QuizHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        dbase = db;
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
                + " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
                + KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT)";
        db.execSQL(sql);
        addQuestion();

        // db.close();
    }
    private void addQuestion() {
        Question q1 = new Question("1. 5+2 = ?", "7", "8", "6", "7");
        this.addQuestion(q1);
        Question q2 = new Question("2. 2+18 = ?", "18", "19", "20", "20");
        this.addQuestion(q2);
        Question q3 = new Question("3. 10-3 = ?", "6", "7", "8", "7");
        this.addQuestion(q3);
        Question q4 = new Question("4. 5+7 = ?", "12", "13", "14", "12");
        this.addQuestion(q4);
        Question q5 = new Question("5. 3-1 = ?", "1", "3", "2", "2");
        this.addQuestion(q5);
        Question q6 = new Question("6. 0+1 = ?", "1", "0", "10", "1");
        this.addQuestion(q6);
        Question q7 = new Question("7. 9-9 = ?", "0", "9", "1", "0");
        this.addQuestion(q7);
        Question q8 = new Question("8. 3+6 = ?", "8", "7", "9", "9");
        this.addQuestion(q8);
        Question q9 = new Question("9. 1+5 = ?", "6", "7", "5", "6");
        this.addQuestion(q9);
        Question q10 = new Question("10. 7-5 = ?", "3", "2", "6", "2");
        this.addQuestion(q10);
        Question q11 = new Question("11. 7-2 = ?", "7", "6", "5", "5");
        this.addQuestion(q11);
        Question q12 = new Question("12. 3+5 = ?", "8", "7", "5", "8");
        this.addQuestion(q12);
        Question q13 = new Question("13. 0+6 = ?", "7", "6", "5", "6");
        this.addQuestion(q13);
        Question q14 = new Question("14. 12-10 = ?", "1", "2", "3", "2");
        this.addQuestion(q14);
        Question q15 = new Question("15. 12+2 = ?", "14", "15", "16", "14");
        this.addQuestion(q15);
        Question q16 = new Question("16. 2-1 = ?", "2", "1", "0", "1");
        this.addQuestion(q16);
        Question q17 = new Question("17. 6-6 = ?", "6", "12", "0", "0");
        this.addQuestion(q17);
        Question q18 = new Question("18. 5-1 = q?", "4", "3", "2", "4");
        this.addQuestion(q18);
        Question q19 = new Question("19. 4+2 = 19?", "6", "7", "5", "6");
        this.addQuestion(q19);
        Question q20 = new Question("20. 5+1 = ?", "6", "7", "5", "6");
        this.addQuestion(q20);
        Question q21 = new Question("5-4 = ?", "5", "4", "1", "1");
        this.addQuestion(q21);
        // END


    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
        // Create tables again
        onCreate(db);
    }
    // Adding new question
    public void addQuestion(Question quest) {

        // SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_QUES, quest.getQUESTION());
        values.put(KEY_ANSWER, quest.getANSWER());
        values.put(KEY_OPTA, quest.getOPTA());
        values.put(KEY_OPTB, quest.getOPTB());
        values.put(KEY_OPTC, quest.getOPTC());
        // Inserting Row
        dbase.insert(TABLE_QUEST, null, values);
    }
    public ArrayList<Question> getAllQuestions() {
        ArrayList<Question> quesList = new ArrayList<Question>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
        dbase = this.getReadableDatabase();
        Cursor cursor = dbase.rawQuery(selectQuery, null);
        // looping through all rows and adding to list


        if (cursor.moveToFirst()) {
            do {
                Question quest = new Question();
                quest.setID(cursor.getInt(0));
                quest.setQUESTION(cursor.getString(1));
                quest.setANSWER(cursor.getString(2));
                quest.setOPTA(cursor.getString(3));
                quest.setOPTB(cursor.getString(4));
                quest.setOPTC(cursor.getString(5));
                quesList.add(quest);

            } while (cursor.moveToNext());
        }
        // return quest list
        return quesList;
    }
}
ArrayList<Question> toSelectFrom = new ArrayList<Question>();
toSelectFrom.addAll(quesList);
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size()));
toSelectFrom.remove(toSelectFrom.indexOf(currentQ));
package com.example.testing;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class QuestionActivity extends Activity{

    ArrayList<Question> quesList;
    ArrayList<Question> toSelectFrom; // <--- HERE
    int score = 0;
    int qid = 0;
    int lives = 5;




    Question currentQ;
    TextView txtQuestion, times, scored, livess;
    Button button1, button2, button3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        QuizHelper db = new QuizHelper(this);  // my question bank class
        quesList = db.getAllQuestions();
        toSelectFrom = new ArrayList<Question>(); // <--- HERE
        toSelectFrom.addAll(quesList); // <--- HERE
        Random random = new Random();// this will fetch all quetonall questions
        currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
        toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
        txtQuestion = (TextView) findViewById(R.id.txtQuestion);
        // the textview in which the question will be displayed
        // the three buttons,
        // the idea is to set the text of three buttons with the options from question bank
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);

        livess = (TextView) findViewById(R.id.livess);
        // the textview in which  will be displayed
        scored = (TextView) findViewById(R.id.score);
        // the timer
        times = (TextView) findViewById(R.id.timers);
        // method which will set the things up for our game
        setQuestionView();
        times.setText("00:02:00");
        // A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
        CounterClass timer = new CounterClass(60000, 1000);
        timer.start();
        // button click listeners
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // passing the button text to other method
                // to check whether the anser is correct or not
                // same for all three buttons
                getAnswer(button1.getText().toString());
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button2.getText().toString());
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button3.getText().toString());
            }
        });
    }
    public void getAnswer(String AnswerString) {
        if (currentQ.getANSWER().equals(AnswerString)) {
            // if conditions matches increase the int (score) by 1
            // and set the text of the score view
            score++;
            scored.setText("Score : " + score);




        } else if(lives > 1){
            lives--;
            livess.setText("Lives: " + lives);


        }

        else {
            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();

        }

        {


        }
        if (qid < 20) {
            // if questions are not over then do this
            Random random = new Random();
            currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
            toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
            setQuestionView();
        } else {
            // if over do this
            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();
        }
    }
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    public class CounterClass extends CountDownTimer {
        public CounterClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }
        @Override
        public void onFinish() {
            times.setText("Time is up");
            Intent intent = new Intent(QuestionActivity.this,
                    Result_Activity_TimesUp.class);
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();
        }
        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            long millis = millisUntilFinished;
            String hms = String.format(
                    "%02d:%02d:%02d",
                    TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
                            .toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis)
                            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
                            .toMinutes(millis)));
            System.out.println(hms);
            times.setText(hms);
        }
    }
    private void setQuestionView() {
        // the method which will put all things together
        txtQuestion.setText(currentQ.getQUESTION());
        button1.setText(currentQ.getOPTA());
        button2.setText(currentQ.getOPTB());
        button3.setText(currentQ.getOPTC());
        qid++;
    }
}
private final Random mRandom  = new Random();
List<Integer> values = new ArrayList<>(20);
for (int i = 0; i < values; ++i) {
    values.add(i);
}
private int getNextRandom(List<Integer> list) {
    int index = mRandom.nextInt(list.size());
    int value = list.remove(index);
    return value;
}