簡體   English   中英

arraylist的索引問題(Android Studio)

[英]Index issue on arraylist (Android Studio)

我正在嘗試創建一個簡單的游戲,使用媒體播放器來猜測歌曲的標題,該播放器根據android studio中基於arraylist的編號從數組歌曲中獲取內容。 因此,我在開頭聲明了一個索引,該索引對於每個隨機變量都增加1,並且每當用戶單擊答案(使用onClick方法)時也會發生。

ImageButton play, answer1, answer2, answer3;
int[] song = new int[] {R.raw.beautifulithurts, R.raw.iwontletyouwalkaway, R.raw.lebihindah, R.raw.ruletheworld, R.raw.sweetescape, R.raw.thatgirl, R.raw.thisislivingnow, R.raw.thislife, R.raw.thousandmiles, R.raw.u};
int[] image = new int[] {R.drawable.lvlaa, R.drawable.lvlab, R.drawable.lvlac, R.drawable.lvlad, R.drawable.lvlae, R.drawable.lvlaf, R.drawable.lvlag, R.drawable.lvlah, R.drawable.lvlai, R.drawable.lvlaj};
ArrayList<Integer> numbers = new ArrayList<>();
ArrayList<Integer> cloning = new ArrayList<>();
int index = 0, a = 0, b = 1, c = 2, random = 0, x = 0, y = 0, z = 0, benar = 0, salah = 0;
MediaPlayer mp;  

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

        play = (ImageButton) findViewById(R.id.play);
        answer1 = (ImageButton) findViewById(R.id.answer1);
        answer2 = (ImageButton) findViewById(R.id.answer2);
        answer3 = (ImageButton) findViewById(R.id.answer3);

        for (int i = 0; i <= song.length; i++) {
            numbers.add(i);
        }
        Collections.shuffle(numbers);

        random();

        play.setOnClickListener(this);
        answer1.setOnClickListener(this);
        answer2.setOnClickListener(this);
        answer3.setOnClickListener(this);
    }

    public void prepareAnswer() {...}

    public void random() {
        mp = MediaPlayer.create(this, song[numbers.get(index)]);
        mp.start();
        prepareAnswer();
        answer1.setImageResource(image[x]);
        answer2.setImageResource(image[y]);
        answer3.setImageResource(image[z]);
        index++;
    }

    @Override
    public void onClick(View v) {...}
}

但是每次我重新啟動游戲時,logcat都會顯示一個錯誤:數組索引超出范圍(大小:10 index:10)。 每次重新啟動游戲時,如何處理此錯誤並將索引重置為0?

使用下面的代碼,而不是你的.....

for (int i = 0; i < song.length; i++) {
            numbers.add(i);
        }

注意:-問題是您要在此處添加額外的編號,並從不存在的song數組列表中訪問該額外的值..例如:-

這首歌有10個值,您正在嘗試訪問第11個值...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM