Exception in thread "main" error in Netbeans

Asked

Viewed 53 times

0

I was making code in Netbeans:

calculator package;

public class Calculator {

public static void main(String[] args) {
 int x = Integer.parseInt(args[1]);
 int y = Integer.parseInt(args [2]);
 sum(x, y);
}
static void sum(int x, int y){
    System.out.println( x + y);
}

}

When I was running appeared this error:

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 1

3 answers

0

Are you sure the position you took is right? Java arrays start with index 0.

Try this:

public static void main(String[] args) {
 int x = Integer.parseInt(args[0]);
 int y = Integer.parseInt(args [1]);
 sum(x, y);
}
static void sum(int x, int y){
    System.out.println( x + y);
}

0

You can also check the data before calling the function.

package calculadora;

import java.util.Scanner;

public class Calculadora {
    public static void main(String[] args) {
        double valor1;
        double valor2;

        if (args.length == 2) {
            valor1 = Double.parseDouble(args[0]);
            valor2 = Double.parseDouble(args[1]);
        } else {
            Scanner scanner = new Scanner(System.in);

            System.out.print("Digite o primeiro valor: ");
            valor1 = scanner.nextDouble();

            System.out.print("Digite o segundo valor: ");
            valor2 = scanner.nextDouble();
        }

        somar(valor1, valor2);
    }

    private static void somar(double valor1, double valor2) {
        System.out.println(valor1 + valor2);
    }
}

In the case here, I programmed to request the data for the user, in case they have not been informed in the program call. You could also show an error message, at last are several options.

0

@Israel Messiah beyond what has been said you are running this application from the terminal? Why these arguments will only be passed if you inform in command by the terminal understands. Or by the IDE itself

Example by terminal

C: App target> java -jar name_do_app.jar ARGUMENTO_1 ARGUMENTO_2

By netbeans has how to do this no need windows Cmd or linux terminal

Browser other questions tagged

You are not signed in. Login or sign up in order to post.