nzec error

NEW TO JAVA -_-

Error now REMOVED…Please clarify the Error (read next Answer given below)

question link: http://www.codechef.com/problems/CARVANS

Please help to remove NZEC ERROR

CODE :-

import java.io.*;

import java.util.*;

public class Main
 
{

	public static void main(String[] args) 
	{
		BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));		
        try
		{
			int t;
		    t = Integer.parseInt(kb.readLine());
		    while(t-->0)
		    {
		    	int n;
			    n = Integer.parseInt(kb.readLine());
			    int[] a = new int[10020];
			    for(int i=0;i<n;i++)
			    {
			    	a[i] = Integer.parseInt(kb.readLine());
			    	
			    }
			    if(n==1)
			    {
			    	System.out.println(1);
			    	continue;
			    }
			    int p = a[0];
			    int count = 1;
			    int k;
			    for(k=1;k<n;k++)
			    {
			    	if(a[k]<p)
			    	{
			    		p = a[k];
			    		count+=1;
			    	}
			    }
			    System.out.println(count);
			
		    }
		
	    }
		catch(IOException ex)
		{
			return;
		}

    }
}
3 Likes

@betlista help to remove nzec error…

ok i have made some changes…now nzec error is removed…

but i don’t know the logic behind that…

i have change the way of taking input into array such as :-

String str[] = kb.readLine().split(" ");

for(int i=0;i< n;i++)

   		    {

	    	a[i] = Integer.parseInt(str[i]);
	    	
		    }
3 Likes

why nzec error is not there now…?

-_-

3 Likes

The NZEC was due to

Exception in thread "main" java.lang.NumberFormatException: For input string: "8 3 6" 

for the sample input of the problem.

This is because kb.readLine() reads the whole line as string. When you are parsing this string as an integer, no problem occurs only when input line has only one integer.

But problem ( this type of exception ) occurs when there are multiple integers ( or anything other than only a single integer ). In the sample case, input is 8 3 6, which is treated as a whole string and Integer.parseInt method can not convert such input to any well defined integer number.This is why it throws exception.

Integer.parseInt(String st) throws NumberFormatException if the string does not contain a parsable integer.

When you modified the way of taking input to

String str[] = kb.readLine().split(" ");    
for(int i=0;i< n;i++){    
            a[i] = Integer.parseInt(str[i]);    
}

the exception was not there because you are reading 8 3 6 as a whole line and splitting it according to the occurrence of " " ( blank space ).

So str[0]=8 (as string not integer), str1=3 and str2=6 (all are strings not integers). Now as the elements of str[] can be parsed as integer individually and separately. This is why you are not getting any exceptions or NZEC.

Read details of Integer.parseInt here and BufferedReader readLine() method here .

1 Like