Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
It works fine on VS Code, but when I run it on the compiler required for our training exam, it shows the above error. What could be the reason?

What does it mean? I am new to programming languages. So please ignore my mistake.

Java
import java.util.Scanner;

public class sum {
    public static void main(String[] args) {

        // Write solution here

        int n = 0, sum = 0;

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

        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();

            if (arr[0] == 0) {
                System.out.println("No elements to sum");
                break;
            }
            else if (arr[0] < 0) {
                System.out.println("Invalid number of elements");
                break;
            }


What I have tried:

The condition was to show "Invalid number of elements" when the user enters a negative value.
Posted
Updated 6-Jan-22 4:53am
v4

Quote:
The condition was to show "Invalid number of elements" when the user enters a negative value.
Then don't you think you should actually do what you were told, instead of blindly accepting the input and trying to create an array with a negative size? 🤦‍♂️

Java
n = sc.nextInt();
while (n < 0) {
    System.out.println("Invalid number of elements");
    n = sc.nextInt();
}

// *NOW* you can create an array of the specified size...
 
Share this answer
 
Negative Array Exception occurs when the input size of the array give is a negative number.
This can be handled by a try-catch block.

Further here you have just checked the array's first element to ensure if it is empty and just checked whether the first element is greater than 0 to check if array is invalid.
Instead use
Java
if (arr.length == 0) {

                System.out.println("No elements to sum");

                break;

            }
else if (arr.length < 0) {

                System.out.println("Invalid number of elements");

                break;

            }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900