You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java数组正负整数分离:将int类型正负值分别存入新数组求助

Split an int Array into Positive and Negative Arrays in Java

Hey there! Welcome to Java and this community—super glad you're here asking questions, that's the best way to learn. Let's walk through exactly how to split your array of positive and negative ints into two separate arrays.

Method 1: Traditional Loop Approach (Great for Learning Basics)

This method is perfect if you want to understand the core logic without relying on newer Java features. Here's how it works:

  1. First, loop through your original array to count how many positive and negative numbers there are. This lets us create arrays of the exact right size (no wasted space!).
  2. Loop through the original array again, and assign each number to the positive or negative array based on its value.
public class SplitArrays {
    public static void main(String[] args) {
        int[] originalArray = {3, -5, 2, -8, 0, 7, -1};
        
        // Step 1: Count positives and negatives
        int positiveCount = 0;
        int negativeCount = 0;
        for (int num : originalArray) {
            if (num > 0) {
                positiveCount++;
            } else if (num < 0) {
                negativeCount++;
            }
            // Note: We're ignoring 0 here—you can adjust this if you want to handle it separately!
        }
        
        // Step 2: Initialize new arrays with correct lengths
        int[] positiveArray = new int[positiveCount];
        int[] negativeArray = new int[negativeCount];
        
        // Step 3: Populate the arrays
        int posIndex = 0;
        int negIndex = 0;
        for (int num : originalArray) {
            if (num > 0) {
                positiveArray[posIndex++] = num;
            } else if (num < 0) {
                negativeArray[negIndex++] = num;
            }
        }
        
        // Print results to verify
        System.out.println("Positive numbers:");
        for (int num : positiveArray) {
            System.out.print(num + " ");
        }
        System.out.println("\nNegative numbers:");
        for (int num : negativeArray) {
            System.out.print(num + " ");
        }
    }
}

Method 2: Java 8+ Stream Approach (Cleaner & More Concise)

If you're ready to explore newer Java features, streams make this task way shorter. Streams let you filter elements in one line:

import java.util.Arrays;
import java.util.stream.IntStream;

public class SplitArraysStreams {
    public static void main(String[] args) {
        int[] originalArray = {3, -5, 2, -8, 0, 7, -1};
        
        // Filter positive numbers
        int[] positiveArray = IntStream.of(originalArray)
                                      .filter(num -> num > 0)
                                      .toArray();
        
        // Filter negative numbers
        int[] negativeArray = IntStream.of(originalArray)
                                      .filter(num -> num < 0)
                                      .toArray();
        
        // Print results
        System.out.println("Positive numbers: " + Arrays.toString(positiveArray));
        System.out.println("Negative numbers: " + Arrays.toString(negativeArray));
    }
}

Quick Note on Zero

I noticed I ignored zero in both examples—since your question only mentioned positive and negative numbers, I figured that's intentional. But if you need to handle zero, you can add a third filter or adjust the conditions (like putting zero in the positive array if that's what you need).

Hope this clears things up! Don't hesitate to ask if you need to break down any part of the code further.

内容的提问来源于stack exchange,提问作者Paojepablo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:47:32