因此,我无法在用户输入数字的数组中查找重复项。我想在输入数组中已有的数字时显示一个对话框。这听起来很简单,但对如何继续这个问题感到困惑。
//Convert the string into an int
num = Integer.parseInt(inputField.getText());
// Add it to the an index
array[index] = num;
// Increment the index variable
index++;
// If the the duplicate exists
for(int i = 0; i < array.length;i++){
if(array[index] == num){
if(array[i - 1] == num){
JOptionPane.showMessageDialog(null,"Array may not contain duplicates ","Array Duplicate",JOptionPane.ERROR_MESSAGE );
break;
}
}
}
答案 0 :(得分:1)
尝试修复您的代码
//Convert the string into an int
num = Integer.parseInt(inputField.getText());
boolean exsist = false;
// If the the duplicate exists
for(int i = 0; i < array.length;i++){
if(array[i] == num){
exsist = true;
JOptionPane.showMessageDialog(null,"Array may not contain duplicates ","Array Duplicate",JOptionPane.ERROR_MESSAGE );
break;
}
}
if(!exsist)
{
// Add it to the an index
array[index] = num;
// Increment the index variable
index++;
}
这样的事情应该起作用
推理是
不使用for循环中的变量i
,这会导致始终检查相同的值
if语句中的检查被破坏,检查没有意义,尝试使用i
或其他更改每个循环的变量来检查多个值
没有必要在测试之前添加值,如果它存在,如果你这样做,你将不得不删除它,之后执行它因此导致更快的代码(即使只是非常非常少)和一个更安全的代码,因为你不能删除值
答案 1 :(得分:1)
// Set orginal to true
boolean orginal = true;
//Convert the string into an int
num = Integer.parseInt(inputField.getText());
// Loop to find the duplicate
for(int i = 0; i < array.length; i++){
// Check if there's a duplicate
for(int j = 0; j < array.length; j++){
// Check if the num is equal to any of the numbers in the array
if(array[j] == num){
// Set orginal to false
orginal = false;
// Throw the duplicate exception
throw new DuplicateValueException(result);
}
}
// If there is no duplicates
if(orginal){
// Add the number to the array
array[index] = num;
// Break out the loop
break;
}
}
// Print the message
System.out.println("array["+index+"] = "+ num);
// Increment the index variable
index++;
答案 2 :(得分:0)
for(int i = 0; i < array.length-1;i++){
if(array[i] == num){
JOptionPane.showMessageDialog(null,"Array may not contain duplicates ","Array Duplicate",JOptionPane.ERROR_MESSAGE );
break;
}
}
试试这个!
但是你的代码会将这个数字添加到数组中,因为你在检查它之前添加它。
答案 3 :(得分:0)
这段代码毫无意义:
// Add it to the an index
array[index] = num;
// Increment the index variable
index++;
for(int i = 0; i < array.length;i++){
if(array[index] == num){
您在数组的num
索引处添加index
int,然后在要检查index+1 == num
的循环中添加。
在你的逻辑中,你应该检查是否index == num
无论如何它没用,你做了:array[index] = num;
。
所以if(array[index] == num)
只能是真的。
我想在输入已经存在的号码时显示对话框 数组
在将数据添加到数组之前,您应该检查重复编号
一般的想法是迭代数组,如果在迭代期间,数组的元素等于num
,则您没有添加num
。
在相反的情况下,如果没有元素等于num
,则必须添加它。
这似乎是一所学校的工作,所以我不会进一步详述解决方案。
答案 4 :(得分:0)
我认为即使对于[5-> 5]
的情况,这也是可行的 index++;
// If the the duplicate exists
if (index > 0) {
for (int i = 0; i < array.length; i++) {
if (array[i] == num) {
JOptionPane.showMessageDialog(null, "Array may not contain duplicates ", "Array Duplicate", JOptionPane.ERROR_MESSAGE);
break;
}
}
}