Domanda

My code below is supposed to print the int 'numComb'. However, it does not. When I run it, nothing happens until I stop the program and then the correct answer appears with 'exit code: 137'. I have read that 137 means it could be an issue with the JVM. However, I also know it can be a result of other things so i would like to know the cause of it in my code and if it has anything to do with it not printing the answer. Could that be the JVM error. Thank you, Sam.

code:

public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int o = 0;
        int numRem = 0;
        int numLim = 0;
        while((sc.hasNextInt())&&(o<1)) {
            int numT = sc.nextInt();
            numLim = sc.nextInt();
            numRem = sc.nextInt();
            o++;
        }
        List<Integer> persons = new ArrayList<Integer>();
        int nextPer;
        while(sc.hasNextInt()){
            nextPer = sc.nextInt();
            if(nextPer<=numLim) {
                persons.add(nextPer);
            }
        }
        int ns = persons.size();

        int numComb = (factorial(ns)) / ((factorial(numRem)) * (factorial(ns - numRem)));//replace with '1' in reply to comment
        System.out.println(numComb);
        System.exit(0);
    }
    public static int factorial(int n) {
        int f = 1;
        for (int i = 1; i <= n; i++) {
            f *= i;
        }
        return f;
    }

This is the whole program because I was requested for it in a comment. Also, my test input was :

3 2 2 1 2 3
È stato utile?

Soluzione

You're error may be here:

    int o = 0;
    int numRem = 0;
    int numLim = 0;
    while((sc.hasNextInt())&&(o<1)) {
  ----> int numT = sc.nextInt();  // You are re-declaring numT
        numLim = sc.nextInt();
        numRem = sc.nextInt();
        o++;
    }

You can avoid coding errors like this by adding more white space, where appropriate.

For example, I would have written your code in this format:

int o =         0;
int numRem =    0;
int numLim =    0;

while( sc.hasNextInt() && (o < 1) )
{
    int numT =  sc.nextInt();
    numLim =    sc.nextInt();
    numRem =    sc.nextInt();

    o++;
}

By following a coding style / guideline it will not only make it easier for yourself to read the code but others as well.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top