Java 图像不断重复,尽管它已经随机化了
我正在开发一个简单的游戏,所有的图像都是随机的。我注意到一些图像是重复的,虽然我已经把随机代码。我对Java还是新手。我希望有人能帮我解决问题。下面是我的代码Java 图像不断重复,尽管它已经随机化了,java,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,Ac
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;
}
}
import java.awt.*;
导入java.awt.event.*;
导入java.sql.*;
导入java.util.Random;
导入javax.swing.*;
公共类Task1扩展了JFrame,实现了KeyListener、ActionListener{
JFrame=新JFrame(“FYP”);
JTextField textField=新的JTextField();
JButton btnNext=新JButton(“下一步”);
整数和=0;
int Error=0;int total_test=0;
静态字符串输入;
静态整数指数;
字符串[]imgFileHP={“1.jpg”、“3.jpg”、“4.jpg”、“7.jpg”、“9.jpg”、“10.jpg”、“12.jpg”、“16.jpg”、“17.jpg”、“18.jpg”};
字符串[]imgNo={“5”、“4”、“6”、“3”、“5”、“3”、“4”、“4”、“6”、“6”};
int-no;
Random rand=新的Random();
公共任务1(字符串inputID)
{
框架尺寸(22002500);
frame.setLocationRelativeTo(空);
frame.setVisible(true);
frame.getContentPane().setLayout(新的BorderLayout(0,0));
任务(inputID);
}
公共无效任务(字符串inputID)
{
JPanel面板=新的JPanel();
JLabel labelUsername=新的JLabel(“”);
frame.getContentPane().add(面板,BorderLayout.CENTER);
面板.立根背景(颜色.白色);
Collections.shuffle(Arrays.asList(imgFileHP));
Set uniqueList=new HashSet();//这将创建编号为0到9的列表
对于(整数计数=0;计数=10){
//添加结果页面以查看分数
//任务2(总和、误差);
System.out.println(“正确:“+sum+”不正确:“+Error”);
frame.dispose();
}否则{
btnNext.removeActionListener(此);
frame.getContentPane().removeAll();
getContentPane().removeAll();
任务(inputID);
}
}
公共静态void main(字符串参数[]){
Task1 a=新Task1(inputID);
}
@凌驾
按下公共无效键(按键事件e){
//TODO自动生成的方法存根
}
@凌驾
公共无效密钥已释放(密钥事件e){
//TODO自动生成的方法存根
}
@凌驾
public void keyTyped(KeyEvent e){
//TODO自动生成的方法存根
}
公共静态布尔值isNumeric(字符串str)
{
尝试
{
整数值(str);
}
捕获(NumberFormatException nfe)
{
返回false;
}
返回true;
}
}
编辑零件(但部分图像仍在重复。)
Collections.shuffle(Arrays.asList(imgFileHP));
Set uniqueList=new HashSet()//这将创建编号为0到9的列表
对于(int count=0;count,这里是随机数的工作原理。尽管您提到了rand.nextInt(10);
,但每次调用它时,java中没有预定义的规则,它必须生成唯一的数字,而不是重复先前生成的数字
例如:
当你打电话给-
int index=rand.nextInt(10);//索引可以是2
index=rand.nextInt(10);//现在值也可以是2
因此,您需要做的是,每次调用random时,都必须添加一段额外的代码来检查唯一性
由于您希望生成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
}
}
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
}
}
for(int count=0;count以下是随机数的工作原理。尽管您提到了rand.nextInt(10);
,但每次调用它时,java中没有预定义的规则,它必须生成唯一的数字,而不是重复先前生成的数字
例如:
当你打电话给-
int index=rand.nextInt(10);//索引可以是2
index=rand.nextInt(10);//现在值也可以是2
因此,您需要做的是,每次调用random时,都必须添加一段额外的代码来检查唯一性
由于您希望生成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
}
}
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
}
}
for(int count=0;count)您所说的“某些图像被重复”到底是什么意思?您每次都会选择一个随机数-因此,是的,您可以多次获得一个图像,就像您多次滚动一个常规骰子一样,您希望多次看到相同的数字。如果您希望每个图像只显示一次,也许您应该基本上对其进行洗牌,然后通过洗牌集合,而不是选择新的每次随机数?你能告诉我怎么做吗?我读过关于随机数的书,但我不能把它应用到我的编码中。这是一个相当广泛的问题描述。我会使用一个列表而不是一个数组,并使用集合。随机数。请注意,我不会有两个数组,而是有一个列表,其中每个元素都在li中st包含正确的答案和图像的文件名…如果您对数组没有异议,可以执行Collections.shuffle(Arrays.asList(myArrayOfBothImageAndNumber))
。在actionPerformed方法中,应将Integer.valueOf更改为Integer.parseInt
。将两个int值与=
进行比较非常重要