Scanner Class


i usually use scanner class in java to read inputs if they are to be read from a single line where the numbers/strings are separated by spaces

like 2 3 4 5

in most of such cases i encounter runtime error(nzec)

after a lot of trials…i realized that the following part of the code was the cause of the error

if(sc.hasNextInt())

{

int n=sc.nextInt();

}

why is it causing an error??

are there any alternatives?

I don’t see why it should be causing a compilation error, but as a head’s up, ‘n’ scope is only that ‘if’ loop.

This code does what it looks like you are trying to make it do.
If you enter a double, the loop quits

import java.util.Scanner;

public class NextInt
{

public static void main(String[] args)
{

Scanner sc = new Scanner(System.in);
int n = 0;
boolean theBoolean = true;

while(theBoolean)
{
  System.out.println("Enter number: ");
  
  if(sc.hasNextInt() == true)
    n = sc.nextInt();
  
  else
    theBoolean = false;
}

System.out.println("Last number entered: " + n);

}

}

still doesnt work…heres my code…

http://www.codechef.com/viewsolution/2048370

this was the question… CodeChef: Practical coding for everyone

works on my machine… gives nzec error on codechef!

Hello

In contests avoid using scanner at all costs ( I don’t use it at all, BufferedReader and BufferedWriter handle IO operations pretty well ) . Instead use other Reader classes like BufferedReader, they’re easy to implement and fast enough for contests. Scanner will most likely cause TLE even on a good solution in the large problems.

And dude in the code you posted you are using two objects two read standard input, don’t do that. you are reading the number the BufferedReader object to read the number of test files and the Scanner object to read the rest. I didn’t test it but that could possibly be the reason you are getting NZEC.

just use split function…