简体   繁体   中英

how to return positive values of original array into a new array

I'm supposed to declare a 15 integer array and return a second array containing the positive integers of the original array. I'm having trouble returning the second array from the method.

    import java.util.Scanner;
    public class array4
    {
      public static void main(String [] args)
      {
        int [] num = new int[15]; int [] positives = new int [15];
        getInput(num);
        positives = getPositives(num);
        printResults(num, positives);
      }
      public static void getInput(int [] num){
        int x;
        Scanner kbd = new Scanner(System.in);
        System.out.println("Enter 15 integers");
        for(x = 0; x < 15; x++)
    num[x] = kbd.nextInt();

   }
  public static int getPositives(int [] num){
    int position = 0;  
    int [] positive = new int [15];
    for(int i =0; i < num.length; i++){  

      if(num[i] >=0) {
        positive[position] = num[i];  
        position++;  }}
    return positive;
  }


  public static void printResults(int [] num, int [] positives){
    System.out.println("You entered"); int x;
    for(x = 0; x < num.length; x++)
    System.out.println(num[x]);
    System.out.println("Your positive integers are ");
    for(x = 0; x < positives.length; x++)
    System.out.println(positives[x]);}}

It is public static int[] getPositive() . The return type is an array of integers, but you declared it as int .

In getPositive you are returning an int rather than an int[]

I think your approach is flawed though.

If you create an ArrayList and put the positive numbers in there, then turn that list into an Array, you won't have any empty places in your array.

You need to declare getPositive to return an array:

public static int[] getPositive(int [] num){

Also, you don't need to initialize positive in the main() method. That just allocates an array the will be discarded.

Your method must return integer array and not a single integer value. Here is modified piece of code :

 public static int[] getPositive(int [] num){
int position = 0;  
int [] positive = new int [15];
for(int i =0; i < num.length; i++){  

  if(num[i] >=0) {
    positive[position] = num[i];  
    position++;  }}
return positive; // Wont give compilation error now

}

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