简体   繁体   中英

About saving and printing distinct numbers in an array

before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.

package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {


public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] numArray = new int[10];
    int d = 0;
    System.out.println("Enter Ten Numbers: ");
    for(int i = 0; i < numArray.length; i++){
        int num = input.nextInt();
        if(inArray(numArray,num,numArray.length)){
            numArray[i] = num;
            d++;

        }

    }
    System.out.println("The number of distinct numbers is " + d);
    System.out.print("The distinct numbers are: ");
    for(int i = 0; i < d; i++){
        System.out.print(numArray[i] + " ");
    }


}
public static boolean inArray(int[] array, int searchval, int numvals){
    for (int i =0; i < numvals; i++){
        if (searchval == array[i]) return false;
    }
    return true;
}

}

You can use a set to identify distinct values:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Set<Integer> distinctNumbers = new LinkedHashSet<>();

    System.out.println("Enter ten Numbers: ");

    for (int i = 0; i < 10; i++) {
        int number = input.nextInt();
        distinctNumbers.add(number);
    }
    System.out.println("The number of distinct numbers is " + distinctNumbers.size());
    System.out.print("The distinct numbers are: ");

    for (Integer number : distinctNumbers){
        System.out.print(number + " ");
    }

}

If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.

Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM