0

One of my Java assignments is to take numbers from a file and then seperate them to two arrays. One named P (positive numbers) and N (negative numbers.) I have it working for the positive numbers but the negative numbers keep outputting 0s. I have no idea why! Help?

import java.io.*;
import java.util.*;

public class Prog404a {
    public static void main(String[] args) {
        Scanner inFile = null;
        try {
            inFile = new Scanner(new File("prg404a1.dat"));
        } catch (FileNotFoundException e) {
            System.out.println("File not found!!");
            System.exit(0);
        }
        int temp = 0;
        int P[] = new int[23];
        int N[] = new int[23];
        int i = 0;
        while (inFile.hasNext()) {
            temp = inFile.nextInt();
            if (temp < 0) {
                N[i] = temp;
            }
            if (temp > 0) {
                P[i] = temp;
            }
            i++;
        }
        for (int x = 0; x < i; x++) {
            System.out.println(P[x] + "\t" + N[x]);
        }
    }
}

EDIT: Never mind it's not working for positive numbers either. Only a few.

3
  • 5
    You are using the same index for both N and P, so if you have seen 3 positive integers, for example, before the first negative integer, it will be inserted at N[3]. Is that really what you want? Commented Feb 16, 2013 at 23:47
  • 1
    I strongly suggest that you learn how to debug your code. You can do this with the debugger in your IDE or add lots of System.out.println() calls to your code to see what is happening. Commented Feb 16, 2013 at 23:48
  • How are your numbers separated? Can we look at sample data? Commented Feb 16, 2013 at 23:50

1 Answer 1

4

Maybe you are just not counting right?

You should be using two counters, one for positive, one for negative numbers. Otherwise, half of the entries will obviously be 0, because they were never set.

Sign up to request clarification or add additional context in comments.

2 Comments

To elaborate further in case the OP doesn't realise, let's saying you are inputting these numbers [1, 3, -4]. P[0] = 1, P[1] = 3, N[2] = -4 (thus leaving N[0] and N[1] with no values).
Oh my God I get it now! I didn't realise it was raising the counter and the other array wasn't getting a number for that count. I fixed it and it works. Thank you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.