[英]How can I use a method to check if the new element that I want to add to my array hasn't already been added?
Im working on a school project and I am suppose to create a program that will display a 2 x 2 grid of numbers (randomly generated from 1 - 16). 我正在做一个学校项目,我想创建一个程序,该程序将显示2 x 2的数字网格(从1-16随机生成)。 This program will then sort it out step by step. 然后,该程序将逐步对其进行分类。
I am supposed to have a logic check class. 我应该有一个逻辑检查类。
I'm trying to make a method where it will take the value that the main() program wants to add, check to see if its already in the array or not, and return false if that number is already there or true if not. 我正在尝试创建一个方法,该方法将采用main()程序要添加的值,检查其是否已经在数组中,如果该数字已经存在,则返回false,否则返回true。
class LogicStatementsV2 {
//Declare constants
private final int LENGTH_OF_INDEX = 16;
//Create an array of how the index of the array should look like
int[] finalIndex = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
//Creates an array of length 16 which will be filled as the main program uses a random number generator.
int[] buildIndex = new int[LENGTH_OF_INDEX];
/**Method that is called to add a random number if that number hasnt been entered
* @param n The integer that the main class will generate from a random number generator
* @return wether that number is already in the array or not
*/
public boolean addIfValid(int n) {
for (int i = 0; i < 16; i++) {
if (n == buildIndex[i]) return false;
else return true;
}
}
}
For some reason the first to last } keeps saying that a return value is required. 由于某种原因,第一个}一直在说需要返回值。
What am I doing wrong? 我究竟做错了什么?
The else return true;
else return true;
doesn't belong in the loop. 不属于循环。 Only once you've looped through all the elements and found no duplicates can you safely return true: 只有遍历所有元素并且没有发现重复项,您才能安全地返回true:
public boolean addIfValid(int n) {
for (int i = 0; i < 16; i++) {
if (n == buildIndex[i]) return false;
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.