there seems to be a problem in arr[] taking input.
when i give input to arr[] , it's not taking input but storing as 0's in codechef

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


class Codechef
{

    static Scanner sc = new Scanner(System.in);
    static int n =sc.nextInt();
    static int arr[]=new int[n];

    public static void main(String[] args) throws IOException
    {
        Scanner br2 = new Scanner(System.in);
        for(int i =0;i<n;i++)
        {
            if(br2.hasNextInt())
            arr[i]=br2.nextInt();
            System.out.println(arr[i]);
        }


    }
}

input :
5
1 4 3 2 2
expected output:
1 4 3 2 2 but output is 0 0 0 0 0 in codechef

1 Answers

1
Spara On

It's not good idea to have multiple scanners to read from System.in. It seems that you are inserting the whole input at same time so the first scanner will read all of them and when you have nothing for the next scanner so your array would be empty.

This code is cleaner and do what you want:

public class Test {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            if (sc.hasNextInt())
                arr[i] = sc.nextInt();
            System.out.println(arr[i]);
        }
    }
}