-1

The following code works fine But as soon i take any integer input at the beginning it goes in infinite loop. I need the integer value for testcases.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class TestClass {
public static void main(String args[] ) throws Exception {
    Scanner stdin = new Scanner(System.in);
     //HERE I JUST INPUT AN
     // INT VALUE PROGRAM GOES INFINITE LIKE int t = stdin.nextInt();
        long count = 0;     
        String str = stdin.nextLine();
        char[] c = str.toCharArray();
        for(int j=0;j<str.length();j++){
            switch(c[j]){
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                    count++;
                default : break;
            } 
        }
        arrangement(count,str.length());


}
    public static void arrangement(long v,long n){
    long total = fact(n);
    long together = ((combination(v))*(fact(n-1))*2);
    long answer = (total - together);
    if(answer>0)
        System.out.println(answer);
    else
        System.out.println("-1");
}

public static long fact(long n){
long ans;
    if(n==1 || n==0)
        return 1;
    else
        ans = fact(n-1)*(n);
    return ans;
}
public static long combination(long n){
    if(n==0)
        return 0;
    if(n==1)
        return 0;
    if(n==2)
        return 1;
    else
        return ((fact(n))/((fact(n-2))*2));
}

}

why is this problem occuring? any possible runtime error reason>?

torrtuga
  • 41
  • 1
  • 1
  • 3

2 Answers2

0

Try placing a scanner.nextLine(); after nextInt() if you intend to ignore the rest of the line. See this post for a similar issue with nextInt(): Using scanner.nextLine()

Community
  • 1
  • 1
niran
  • 338
  • 1
  • 2
  • 11
0

The reason for the "strange" run time error is that (using the nextInt()) after

$ java TestClass
42

with a return typed after 42, the stdin.nextLine() reads a line of length 0.

arrangement( 0, 0 );

leads to a call of

fact(n-1)

with n == 0, and thence into a rather long infinite recursion. Stack overflow...

I guess you can fix that easily.

laune
  • 30,276
  • 3
  • 26
  • 40