简体   繁体   中英

Displaying odd values in an array

I am trying to display the odd numbers in an array, but only once per number (ie numbers[3] = 3,3,1; would only display 3 and 1 instead of 3, 3 and 1.)

this is the code that I have as of now, the program completely will create an with the specific length entered by the user and then will calculate the max min, and odd values in the array.

import java.util.Scanner;

public class ArrayLab
{
static Scanner input = new Scanner (System.in);

public static void main(String[] args)
{
    System.out.println("Enter the number of numbers: ");
    final int NUMBER_OF_ELEMENTS = input.nextInt();

    double[] numbers = new double[NUMBER_OF_ELEMENTS];
    System.out.println("Enter the numbers: ");

    for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
        numbers[i] = input.nextDouble();
    }
    input.close();

    double max = numbers[0];
    double min = numbers[0];

    for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
        if (numbers[i] > max)
        {
            max = numbers[i];
        }
    }
    System.out.println("The max is: " + max);

    for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
        if (numbers[i] < min)
        {
            min = numbers[i];
        }
    }
    System.out.println("The min is: " + min);

    for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
        if (numbers[i] % 2 != 0)
        {
            System.out.println ("The odd numbers are: " + numbers[i]);
        }
    }

}

}

thanks for any help.

Set<Integer> set = new HashSet<Integer>();
 for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
     if (numbers[i] % 2 != 0)
        {
            set.add(numbers[i]);
        }
    }
System.out.println ("The odd numbers are: " +set);

This can be done a lot simpler using Java8:

double[] d = Arrays.toStream(numbers).filter(d -> (d % 2) == 1).distinct().toArray();

for(double tmp : d)
    System.out.println(tmp);

System.out.println("min: " + Arrays.toStream(numbers).min((a , b) -> new Double(a).compareTo(b)));

System.out.println("max: " + Arrays.toStream(numbers).max((a , b) -> (new Double(a).compareTo(b))));

For you're solution: you never eliminate repeating numbers, thus the duplicates remain in the array until you print all odd numbers and the maximum-number.

This elimination can be done in several ways:

  • Using Java8 as above
  • add all values to a Set , since these don't allow duplicate values
  • eliminate them in your own way (i won't provide any code for this since it's rather complicated to design an efficient solution for this)

Updated solution for what you need. And Please use a better coding standard. Do note the condition check !oddNumbers.contains(numbers[i]) is not very necessary as HashSet never takes any duplicate values.

import java.util.HashSet;
import java.util.Scanner;

public class ArrayLab {
static Scanner input = new Scanner(System.in);

public static void main(String[] args) {
    System.out.println("Enter the number of numbers: ");
    final int NUMBER_OF_ELEMENTS = input.nextInt();

    double[] numbers = new double[NUMBER_OF_ELEMENTS];
    System.out.println("Enter the numbers: ");

    for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
        numbers[i] = input.nextDouble();
    }
    input.close();
    HashSet<Double> oddNumbers = new HashSet<Double>(NUMBER_OF_ELEMENTS);

    double max = numbers[0];
    double min = numbers[0];

    for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }

        if (numbers[i] < min) {
            min = numbers[i];
        }

        if (numbers[i] % 2 != 0 && !oddNumbers.contains(numbers[i])) {
            oddNumbers.add(numbers[i]);
        }
    }
    System.out.println("The max is: " + max);
    System.out.println("The min is: " + min);
    System.out.println("The odd numbers are: " + oddNumbers);
}

}

A more meaningful solution to your approach would be as follows:

int[] tempArray; //temporary array to store values from your original "array"
int count=0;
for(int i=0; i<numbers.length; i++) {
    if(numbers[i]%2 != 0) {
        count++;
    }
}
tempArray = new int[count]; //initializing array of size equals to number of odd digits in your array
int j = 0;
for(int i=0; i<numbers.length; i++) {
    boolean check = true;
    for(int k=0; k<j; k++) {
        if(tempArray[k] == numbers[i]) {
            check = false; //this will prevent duplication of odd numbers
        }
    }
    if(numbers[i]%2 != 0 && check) {
        tempArray[j]=numbers[i];
        j++;
    }
}
//Now print the tempArray which contains all the odd numbers without repetition

A few people have mentioned sets, but there is a different way as well. Simply sort the array, then scan through it, checking each number against the last one printed. ie,

int lastPrinted = 0;

// Sort the array
Arrays.sort(numbers);

System.out.print("The odd numbers are: ");

// Scan through the array
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
    // if it's odd and doesn't match the last one...
    if (numbers[i] % 2 != 0 && numbers[i] != lastPrinted)
    {
        // ...print it and update lastPrinted
        System.out.print( "" + numbers[i] );
        lastPrinted = numbers[i];
    }
}
System.out.println("");

As a side note, you really don't have to scan through the array twice to find your max and min, you can do that in one go.

I think you can use inbuilt hashmap class and its method to achieve the task without affecting the complexity of algorithm to any great extent .

import java.util.HashMap;

public class Hashing {

public static void main(String[] args) {
    //declare a new hasmap
    HashMap<Integer, Integer> map = new HashMap<>();
    //consider Arr as your Array
    int Arr[] = {3,3,1,4,5,5,7,8};
    //traverse through the array
    for(int i=0;i<Arr.length;i++){
        //check if the required condition is true
        if(Arr[i]%2==1){
            /*now we insert the elements in the map but before
              that we have to make sure that we don't insert duplicate values*/
            if(!map.containsKey(Arr[i])){// this would not affect the complexity of Algorithm since we are using hashMap
                map.put(Arr[i], Arr[i]);//We are storing the Element as KEY and as VALUE in the map
            }
        }
    }
    //now We can get these element back from map by using the following statement
    Integer[] newArray = map.values().toArray(new Integer[0]);
    //All the required elements are now present in newArray
    for(int ele:newArray){
        System.out.println(ele);
    }
}

}

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