Home > Enterprise >  Why below code throwing IllegalFormatConversionException error?
Why below code throwing IllegalFormatConversionException error?

Time:11-13

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

public class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        //your code here
    Scanner sc =new Scanner(System.in);
    int N=sc.nextInt();
    int[] arr=new int[N];
    for(int i=0;i<N;i  )
    arr[i]=sc.nextInt();

    Solution s=new Solution();
    s.Answer(arr,N);
    
    }
}
 class Solution
{
  public void Answer(int [] arr,int N)
  {
    int p=0,ne=0,z=0,i=0;
       while(i<arr.length)
       {
         if(arr[i]>0)
           p  ;
         else if(arr[i]<0)
           ne  ;
         else  z  ;
         i  ;
       }
   System.out.printf("%1.4f \n", p/N);
        System.out.printf("%1.4f \n", ne /N);
        System.out.printf("%1.4f\n ", z / N);
  }
}

I have written the above code for the question Given an array of integers of size N integers, the task is to find the ratio of positive numbers, negative numbers, and zeros in the array up to four decimal places.

Examples:

Input: a[] = {2, -1, 5, 6, 0, -3} 
Output: 0.5000 0.3333 0.1667 
There are 3 positive, 2 negative, and 1 zero. Their ratio would be positive: 3/6 = 0.5000, negative: 2/6 = 0.3333, and zero: 1/6 = 0.1667.

I compiled the above code but it showing an Illegalformatexception. But I am not getting why it is showing like that.

I checked all syntaxes which I have used in this code. but I couldn't find that problem.

please help me in solving this plus-minus problem.

CodePudding user response:

package ddd;
import java.util.*;


public class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        //your code here
    Scanner sc =new Scanner(System.in);
    int N= sc.nextInt();
    int[] arr=new int[N];
    for(int i=0;i<N;i  )
    arr[i]=sc.nextInt();

    Solution s=new Solution();
    s.Answer(arr,N);
    
    }
}
 class Solution
{
  public void Answer(int [] arr,int N)
  {
    int p=0,ne=0,z=0,i=0;
       while(i<arr.length)
       {
         if(arr[i]>0)
           p  ;
         else if(arr[i]<0)
           ne  ;
         else  z  ;
         i  ;
       }
   System.out.printf("%1.4f \n", p/(float)N);
        System.out.printf("%1.4f \n", ne/(float)N);
        System.out.printf("%1.4f\n ", z/(float)N);
  }
}

I think just converting N to float would solve your problem.

  •  Tags:  
  • java
  • Related