I was browsing the web for examples on how to partition in Java. I've got to this website that has a detailed example about Partitioning so I've tried to run it on my JCreator Pro.

I've only got one error, but I've tried all I can do to fix it ( Put BufferedReader, import java.io.*, throws IOException ), and It still wouldn't work.

Here's the Error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Partition.main(Partition.java:17)

Here's the Code:

public class Partition { 

    public static void partition(int n) {
        partition(n, n, "");
    }
    public static void partition(int n, int max, String prefix) {
        if (n == 0) {
            System.out.println(prefix);
            return;
        }
  
        for (int i = Math.min(max, n); i >= 1; i--) {
            partition(n-i, i, prefix + " " + i);
        }
    }
  public static void main(String args[]) { 
        int N=Integer.parseInt(args[0]);
        partition(N);
    }

}

Thank you very much!

Recommended Answers

All 4 Replies

@janineXD.
Look carefully the 17th line
int N = Integer.parseInt(args[0]);
this means that parse the input(command line argument) given to Wrapper class Integer.
So to run without exception you should compile like this
java Partition 2


Refer the following site to understand command line line arguments
Command line Argument
Hope you understand the Exception

I still don't get why the code won't work?
can you provide a newer version of the java program that works and doesn't have an error when you compile it?

Thank you!

@JanineXD

There is no mistake in your code.
Problem is when you run that code.

so run the code like this

java Partition 2

When you put this in the code: int N=Integer.parseInt(args[0]); , you are supposed to pass arguments to your program when you run it. (args[0])

Don't expect to copy code from the internet and run it without putting any effort to understand it.

Have you tried the link new_programmer has provided?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.