Java:将数组解析为正数组和负数组 [英] Java : Parse array to positive and negative array

查看:140
本文介绍了Java:将数组解析为正数组和负数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我所做的事情,它可以正常工作,但是我不想制作固定数量的负面文章和正面文章,因此代码可以在任何数组上工作:

Below is what i done, and it is working properly, but I want to make no fixed numbers of negative and positive articles , so code can work on any array:

    int[] array = {15, 22, 71, -27, 33, -44, 0, 334, -82};
    int[] negative = new int[3];
    int[] positive = new int[6];
    int n = 0;
    int p = 0;

    for(int i=0;i<array.length;i++){
        if(array[i]<0){
            negative[n] = array[i];
            n++;
        }else{
            positive[p] = array[i];
            p++;
        }
    }
    System.out.println("Negative array : " + Arrays.toString(negative));
    System.out.println("Positive array : " + Arrays.toString(positive));

有什么建议吗?

推荐答案

您可以采用两种不同的方式:

You can follow two different ways:

  • 第一步计算负数和正数,生成负数和正数的数组并填充它们
  • 为正负创建 List ,填充它们并将其转换为数组
  • Count negative and positive at first step, generate the arrays for negative and positives and fill them
  • Create List for positive and negatives, fill them and convert them to arrays

如果没有必要使用正负数组,您还可以将原始数组分为两个列表(而不是两个数组).

If it is not necessary to have arrays of positives and negatives you can also split the original array in two lists (instead of two arrays).

第一种可能性

int numPositives = 0;
int numNegatives = 0;
for(int i=0;i<array.length;i++){
    if (array[i] >= 0) {
        numPositives++;
    } else {
        numNegatives++;
    }
}

int[] negative = new int[numNegatives];
int[] positive = new int[numPositives];
int n = 0;
int p = 0;

for(int i=0;i<array.length;i++){
    if(array[i]<0){
        negative[n] = array[i];
        n++;
    }else{
        positive[p] = array[i];
        p++;
    }
}


第二种可能性

List<Integer> positivesList = new ArrayList<Integer>();
List<Integer> negativesList = new ArrayList<Integer>();

for (int i = 0; i < array.length; i++) {
    if (array[i] >= 0) {
        positivesList.add(array[i]);
    } else {
        negativesList.add(array[i]);
    }
} 
int[] positive = positivesList.toArray(new int[positivesList.size()]);
int[] negative = negativesList.toArray(new int[negativesList.size()]);

这篇关于Java:将数组解析为正数组和负数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆