简体   繁体   English

在数组中显示奇数值

[英]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.) 我试图在数组中显示奇数,但每个数字仅显示一次(即,numbers [3] = 3,3,1;仅显示3和1而不是3、3和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: 使用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 如上所述使用Java8
  • add all values to a Set , since these don't allow duplicate values 将所有值添加到Set ,因为这些值不允许重复值
  • 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. 请注意,条件检查!oddNumbers.contains(numbers [i])并不是非常必要,因为HashSet绝不使用任何重复的值。

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 . 我认为您可以使用内置的hashmap类及其方法来完成任务,而不会在很大程度上影响算法的复杂性。

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);
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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