0

I just started using Java (SE 8)

So here's my code:

public class Foo {
    public static int sum(int[] arr) {
        int ans = 0;
        for (int i = 0; i < arr.length; i++) {
            ans += arr[i];
        }
        return ans;
    }

    public static int[] takeInput() {
        Scanner s = new Scanner(System.in);
        int size = s.nextInt();
        int arr[] = new int[size];
        for (int i = 0; i < size; i++) {
            arr[i] = s.nextInt();
        }
        return arr;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int testCases = s.nextInt();
        while (testCases-- > 0) {
            int arr[] = takeInput();

            System.out.println(sum(arr));
        }
    }

}

For some reason I get a NoSuchElementException

java.util.NoSuchElementException                   
  at line 937, java.base/java.util.Scanner.throwFor            
  at line 1594, java.base/java.util.Scanner.next                  
  at line 2258, java.base/java.util.Scanner.nextInt                      
  at line 2212, java.base/java.util.Scanner.nextInt                       
  at line 18, Solution.takeInput                           
  at line 32, Solution.main
                                                            

Basically have to find sum of elements of each arrays
Input:

2
5
1 2 3 4 5
3
10 20 30

Output:

15 60

What am I doing wrong here?

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
Tanush S
  • 19
  • 2

2 Answers2

1

I think you should use one instance of Scanner.

public class MavenMain {

    private static int sum(int[] arr) {
        int sum = 0;

        for (int i = 0; i < arr.length; i++)
            sum += arr[i];

        return sum;
    }

    private static int[] takeInput(Scanner scan) {
        int[] arr = new int[scan.nextInt()];

        for (int i = 0; i < arr.length; i++)
            arr[i] = scan.nextInt();

        return arr;
    }

    public static void main(String... args) {
        Scanner scan = new Scanner(System.in);
        int testCases = scan.nextInt();

        while (testCases-- > 0) {
            int[] arr = takeInput(scan);
            System.out.println(sum(arr));
        }
    }

}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
-1

Possible answer in here: Scanner error with nextInt()

So for your code

   public static void main (String[] args)
    {
        Scanner s = new Scanner (System.in);
        if(s.hasNext()) {
            int testCases = s.nextInt();
            while (testCases-- > 0)
            {
                int arr[] = takeInput();

                System.out.println (sum (arr));
            }
        }
        s.close();
    }

Would help.

kmcakmak
  • 139
  • 6
  • This will not help, because `Scanner` will wait until `nextInt()`. **P.S.** `new Scanner(System.in)` should not be closed at the end: you close `System.in` and it will no work again. – Oleg Cherednik Jul 11 '21 at 12:52