Rahul Natu
Rahul Natu

Reputation: 1

error in java programming Exception in thread "main" java.lang.NumberFormatException

This is the program to show sum of series 1-(a^2/3!)+(a^4/5!)-(a^6/7!)+..... I used recursion show factorial of number

    import java.io.*;
    class Series{
       public static void main(String args[])throws IOException{
         int n,a;
         double sum=0;
         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
         String str;

         System.out.println("Enter the value of n & a");

         str=br.readLine();
         n=Integer.parseInt(str);
         str=br.readLine();
         a=Integer.parseInt(str);

         for(int i=0;i<=n;i++){
             sum=sum+(Math.pow(-1,i)*(Math.pow(a,2*i)/fact(2*i+1)));
         }
         System.out.println(sum);
      }

      static int fact(int n){
        int  fact=1,i;
        for(i=1;i<=n;i++){
           fact=fact*i;
        }
        return(fact);
      }
   }

output =

Exception in thread "main" java.lang.NumberFormatException: For input string: "3 6"    
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Series.main(Series.java:12)

Please help me out it is showing error in java programming Exception in thread "main" java.lang.NumberFormatException

Upvotes: 0

Views: 3435

Answers (4)

Jayanth
Jayanth

Reputation: 329

readLine() will read characters until a newline is found.

In your case, try entering the value of n and a in newline

or Use a Scanner instead

Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
a = scanner.nextInt();

Upvotes: 0

Manjunath
Manjunath

Reputation: 1685

Try this:-

Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of n & a");
n = sc.nextInt();
a = sc.nextInt();

Upvotes: 1

"3 6" contains a space so java can't convert that to a number. That is why you are getting that error. You can replace all the spaces with "" and then try to convert that to the number

String line = br.readLine().replaceAll("\\s+", "");
//if you only have spaces in either of side. then you can use trim()
int number = Integer.parseInt(line);

But the best way is to replace all non digit characters with ""

String line = br.readLine().replaceAll("\\D+", "");
int no = Integer.parseInt(line);

Upvotes: 2

Vihar
Vihar

Reputation: 3831

Integer.parseInt(str);

this is the erroneous line as str="3 6"(in your case) and it cannot be cast into an Integer.

Upvotes: 2

Related Questions