我不明白用什么来检查数组中的所有值?

时间:2014-11-04 03:36:55

标签: java

import java.util.Scanner;
public class Project10C {
public static void main ( String [] args ) {
Scanner reader = new Scanner(System.in);
int [] finalarray = new int [5];
int [] test = new int [1000];
int x = 1000;
int temp1;

for ( int i = 0; i <= 4;i++){
    System.out.println ( "Input a number between 1 and 25 inclusive: " );
    temp1 = reader.nextInt();
    test[i] = temp1;
    if ( i > 0 ){
        if ( temp1 == test[i] ) {
        System.out.print ("Sorry that number has already been entered.");
                break;

        }
        else {
            finalarray[i]= temp1;

此问题中未包括括号。检查此代码是否已输入数字。我在尝试检查他们输入的数字是否等于现有数组中的值时遇到了困难。在这:

if (temp1 == test[i] ){

据我所知,这只会检查每次都通过这个if语句的当前数组。我应该使用另一个声明吗?如果是这样,我会为for语句的第二个参数添加什么?

3 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点。最简单的方法可能是在主循环中使用另一个循环,如下所示:

for ( int i = 0; i <= 4;i++){
    System.out.println ( "Input a number between 1 and 25 inclusive: " );
    temp1 = reader.nextInt();

    boolean repeated = false;
    for(int j = 0; j < i; j++) {
        if(finalarray[j] == temp1) {
            // the number is already entered.
            repeated = true;
            break;
        }
    }

    if(repeated)
        break;

    // number is not entered before
    finalarray[i] = temp1;
}

实际上,当您正在阅读第i个号码时,您必须检查数组中从0到(i - 1)的每个数字与输入的数字不相等。

但是,如果有很多数字,最好使用像Set这样的数据结构。只需将每个数字添加到集合中,然后您就可以轻松检查以前是否输入了新号码:

Set<Integer> numbers = new TreeSet<Integer>();

for(int i = 0; i < n; i++) {
    temp1 = reader.nextInt();

    if(numbers.contains(temp1)) {
        // already entered
        break;
    }

    // number is not entered before
    // add it to our array
    finalarray[i] = temp1;

    // also put it in the set for future checks
    numbers.add(temp1);
}

答案 1 :(得分:1)

您需要另一个for循环来比较最终数组的先前元素和我在解决方案中建议的输入输入。此外,循环将始终从0 to i ---关键的东西迭代!

解决方案如下: -

for ( int i = 0; i <= 4;i++){
System.out.println ( "Input a number between 1 and 25 inclusive: " );
temp1 = reader.nextInt();
for( int j=0;j<i;j++){
if(temp1==finalarray[j]){
 System.out.println("Sorry that number has already been entered.");
 break;
}
else 
 finalarray[i]= temp1;

}
}

答案 2 :(得分:0)

您是否必须使用原始数组,还是可以使用ArrayList?如果你可以使用ArrayList:

List<int> myArrayList = new ArrayList();

for (int i = 0; i <= 4; i++){
    System.out.println ( "Input a number between 1 and 25 inclusive: " );
    temp1 = reader.nextInt();

    /* The array list already has the input number. */
    if (myArrayList.contains(temp1)) {
        System.out.print ("Sorry that number has already been entered.");
        break;
    /* The array list does not contain the input number. */
    } else
        myArrayList.add(temp1);
}

另外,您是否只想输入4位数字?