int arr []在codechef中未正确输入,但在Eclipse中工作正常

时间:2019-05-18 15:11:36

标签: java

arr []接受输入似乎有问题。
当我将输入提供给arr []时,它不接受输入,而是将其存储为0,保存在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]);
        }


    }
}

输入:
5
1 4 3 2 2
预期输出:
1 4 3 2 2 但是在codechef中输出为0 0 0 0 0

1 个答案:

答案 0 :(得分:1)

要从System.in读取多个扫描仪不是一个好主意。似乎您正在同时插入整个输入,因此第一个扫描器将读取所有输入,而当下一个扫描器没有任何输入时,您的数组将为空。

此代码更干净,可以执行您想要的操作:

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]);
        }
    }
}
相关问题