Reputation: 69
import java.util.Scanner;
public class argu {
public static void main(String[] args)
{
int number = Integer.parseInt(args [0]);
int x = number % 2;
if (x == 0) {
System.out.println("It is even");
}
else {
System.out.println("It is not even");
}
}
}
I have been trying to code this program to make an user enter a number, (that is the args [0] for), however, it sends this error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at argu.main(argu.java:7)
The fix I made was
import java.util.Scanner;
public class argu {
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
int number = scan.nextInt();
int x = number % 2;
if (x == 0) {
System.out.println("It is even");
}
else {
System.out.println("It is not even");
}
}
}
I want to know if there is a way to user args [0] instead of the Scanner method. Keep in mind, I am a beginner, so I am sorry some of the stuff is wrong
My other question is to help me analyze the method Scanner scan = new Scanner (System.in);
scan is the variable? Scanner is the method? I am confused with variables, parameters, and methods. If you could help me differentiate one from the other.
Thank you.
Upvotes: 0
Views: 2683
Reputation: 830
args[0]
indicates the arguments when used to start up the program - this is done using commands.
Say you ran this command through cmd or the terminal:
java -jar myjar.jar 5
The value of args[0]
would be 5, because 5 in the command is an argument. The argument is passed to args[]
. Adding another argument would go to args[1]:
java -jar myjar.jar 5 10
args[1]
would equal 10.
See @Ruets answer for details on how to use arguments in Eclipse.
You get your error because args[0] is not existent - the command would look more something like this:
java -jar myjar.jar
Upvotes: 1
Reputation: 31339
In eclipse to add an argument to the program you have to add a run configuration with that argument.
That's in the Run
-> Run Configurations...
-> pick your configuration (probably "main" or "argu") -> Arguments
(tab) -> add arguments in Program Arguments
(top text field, Name your configuration something meaningful).
Now use this configuration to run the program. You can have many different configurations obviously.
Upvotes: 2