尽管图像已经随机化,但图像仍在继续重复

时间:2016-10-16 15:46:53

标签: java

我正在开发一个简单的游戏,其中所有图像都是随机的。我注意到虽然我已经放了随机码,但是有些图像被重复了。我还是Java新手。我希望有人可以帮助我解决我的问题。以下是我的编码。

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Random;
import javax.swing.*;

public class Task1 extends JFrame implements KeyListener,ActionListener {
    JFrame frame = new JFrame("FYP");
    JTextField textField = new JTextField();
    JButton btnNext = new JButton("NEXT"); 

    int sum=0;
    int Error=0;int total_test = 0;
    static String inputID;
    static int index;
    String[] imgFileHP = {"1.jpg","3.jpg","4.jpg","7.jpg","9.jpg","10.jpg","12.jpg","16.jpg","17.jpg","18.jpg"};
    String[] imgNo = {"5","4","6","3","5","3","4","4","6","6"};
    int randomNo;
    Random rand = new Random();

public Task1(String inputID)
{
    frame.setSize(2200,2500);
    frame.setLocationRelativeTo(null);  
    frame.setVisible(true);
    frame.getContentPane().setLayout(new BorderLayout(0, 0));       

    Task(inputID);
}

public void Task(String inputID)
{
    JPanel panel = new JPanel();
    JLabel labelUsername = new JLabel("");

    frame.getContentPane().add(panel, BorderLayout.CENTER);
    panel.setBackground(Color.WHITE);

    Collections.shuffle(Arrays.asList(imgFileHP));
    Set<Integer> uniqueList = new HashSet<Integer>();//This would create list with the number 0 to 9
    for(int count=0;count<imgFileHP.length;count++){
        uniqueList.add(count);
        labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[count])));
        if(!uniqueList.isEmpty()){
            index =  (int) (Math.random() * (upper - lower)) + lower;

            if(uniqueList.contains(index)){

               uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
               System.out.println(imgFileHP[r]);//This printf statement is just for your reference
            }   
        }


    }
    textField.setText("");
    textField.setColumns(10);
    textField.addKeyListener(this);     

    btnNext.addActionListener(this);

    panel.add(labelUsername);
    panel.add(textField);
    panel.add(btnNext);
    frame.setVisible(true);
}

public void actionPerformed(ActionEvent ae)
{

    if(!textField.getText().equals("")){
        total_test += 1;
        if(isNumeric(textField.getText())){
            //********************Correct Integer**********************
            if(Integer.valueOf(imgNo[randomNo])==Integer.valueOf(textField.getText())){
                //********************Correct Answer**********************
                System.out.println("Correct");
                sum+=1;
            }else{
                //********************Incorrect Answer**********************
                System.out.println("Incorrect");
                Error+=1;
            }
            refreshFrame();
        }else{
            //********************Incorrect Integer/Alphabet**********************
            System.out.println("Invalid");
            Error+=1;
            refreshFrame();
        }
    }else{
        System.out.println("Null Input");
    }
    //System.out.println(Integer.valueOf(imgNo[randomNo]));
}
public void refreshFrame(){
    if(total_test>=10){
        // add result page to see how many score
        //Task2(sum, Error);
        System.out.println("Correct: "+sum+" Incorrect: "+Error);
        frame.dispose();
    }else{
        btnNext.removeActionListener(this);
        frame.getContentPane().removeAll();
        getContentPane().removeAll();
        Task(inputID);
    }

}

    public static void main(String args[]) {
        Task1 a = new Task1(inputID);
    }
    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub

    }
    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }
    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    public static boolean isNumeric(String str)  
    {  
      try  
      {  
          Integer.valueOf(str);  
      }  
      catch(NumberFormatException nfe)  
      {  
        return false;  
      }  
      return true;  
    }

}

编辑部分(但部分图像仍在重复。)

Collections.shuffle(Arrays.asList(imgFileHP));
    Set<Integer> uniqueList = new HashSet<Integer>();//This would create   list with the number 0 to 9
    for(int count=0;count<imgFileHP.length;count++){
        uniqueList.add(count);
    }

        if(!uniqueList.isEmpty()){
            index =  (int) (Math.random() * (upper - lower)) + lower;
            randomNo = index;
            if(uniqueList.contains(index)){
               labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[index]))); 
               uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
               System.out.println(imgFileHP[r]);//This printf statement is just for your reference
            }   
        }

1 个答案:

答案 0 :(得分:0)

以下是Random的工作原理。即使您已经提到rand.nextInt(10);,但每次调用它时,java中都没有预先定义的规则,它必须生成唯一的数字而不是先前生成的数字。

例如: 你打电话的时候 - int index = rand.nextInt(10); //索引可能是2 index = rand.nextInt(10); //现在,值也可以是2

所以你需要做的就是每次调用随机数时都需要添加额外的代码来检查唯一性。

因为您要生成介于0到10之间的数字。请尝试以下代码,这可能有助于您理解。

String[] imgFileHP = {"1.jpg","3.jpg","4.jpg","7.jpg","9.jpg","10.jpg","12.jpg","16.jpg","17.jpg","18.jpg"};
        int upper = imgFileHP.length;
        int lower = 0;
        int r=0;
        int index=0;

        Set<Integer> uniqueList = new HashSet<Integer>();//This would create list with the number 0 to 9
        for(int count=0;count<imgFileHP.length;count++){
            uniqueList.add(count);
        }



        if(!uniqueList.isEmpty()){
            index =  (int) (Math.random() * (upper - lower)) + lower;

            if(uniqueList.contains(index)){

                uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
                System.out.println(imgFileHP[r]);//This printf statement is just for your reference
            }   
        }

另一种更简单的方法是使用Collections.Shuffle,如下所示:

Collections.shuffle(Arrays.asList(imgFileHP));

Collection.shuffle()的示例。

假设你有一个数组String[] arr = {"abc","def","xyz","bla"}

当你Collections.shuffle(Arrays.asList(arr));

然后从索引0到3打印数组。数组可能会被洗牌:{"def","bla","abc","xyz"}

**编辑2:**基于您在主代码中编辑的解决方案:

  for(int count=0;count<imgFileHP.length;count++){//first add the counters into List 
            uniqueList.add(count);
        }


        if(!uniqueList.isEmpty()){
            index =  (int) (Math.random() * (upper - lower)) + lower;

            if(uniqueList.contains(index)){
               labelUsername.setIcon(new ImageIcon(getClass().getResource("/image/" + imgFileHP[index])));
               uniqueList.remove(index);//particular number is delete from the list so that duplicate images doesnt show up
               System.out.println(imgFileHP[r]);//This printf statement is just for your reference
            }   
        }