I have a problem in NetBeans with Command-Line Arguments, when run this code it says
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Note I put an argument in command line for NetBeans
public class NewEmpty1
{
public static void main(String arg[]){
System.out.println(arg[0]);
}
}
What is wrong ?
goto Project-Property-Run here you will see the option
main class
arguments
now make sure you are accessing the correct main class....after this option you have button to browse the class path. select it and then select the arguments finally you should be able to run the program...cheers!
Ashish
You have not passed any arguments..
And if you have passed arguments then it may be because you are invoking another class main method in the same package
the best way would be to iterate..
for(string s:arg)
System.out.println(s);
or
for(int i=0;i<arg.length();i++)
System.out.println(arg[i]);
subscript the string beyond its index is undefined.
this is your case. args[] is empty.
check this How to pass cmd line argument
public class NewMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int argslen=args.length;
int argsValue[] = new int[argslen];
for (String i:args) {
int d = 0;
argsValue[d]=Integer.parseInt(i);
System.out.print(argsValue[d]+"\t"+"\n");
}
}
}
Related
I want to print the length of the first argument(args[0]) but getting ArrayOutOfBountException :
public class Main {
public static void main(String[] args){
args[0] = "Hello";
System.out.println(args[0].length());
}
}
Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.main(Main.java:3)
When you write the code,
public class Main {
public static void main(String[] args){
args[0] = "Hello";
System.out.println(args[0].length());
}
}
At this point args[0]="Hello";, If your args a String array is not initialized then, while execute I'm supposed to think that you may have used the command in such a way java Main to execute your basic program.
Which cause the error, You have not passed any argument through command line so your String[] args is not initialized yet and it is not able to store your String "Hello" inside array args[0] and you are trying to print an empty array and throw the Exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.main(Main.java:3)
Update Answer:
Now Yes, You can use that to verify the String args length before print.
public class Main {
public static void main(String[] args){
if(args.length !=0){
System.out.println(args[0].length());
}else{
args = new String[1]; //Initilize first
args[0] = "Hello"; //Store value in array element
System.out.println(args[0].length()); //Print it.
}
}
}
First, check if there is an argument. Then print the length. It's not a good idea to change the values in the argument array either. Something like
if (args.length > 0) {
System.out.println(args[0].length);
} else {
System.out.println(0);
}
should do it.
Here array of String does not have any initialized objects and args has 0 element. That's why it is recommended to check whether does args have any element or not. Then, proceed further accordingly. This is how code looks like.
public class Main {
public static void main(String[] args){
if(args.length !=0){
// do something
}else{
// args doesn't have element.
return ;
}
}
}
You need to check first if an argument is even present.If there is no argument passed and you try to access any element, it will throw ArrayIndexOutOfBoundsException. Also, you should avoid assign any hardcoded value to the elements in array. The code to access 1st element can be something like below:-
if(args.length>0){
System.out.println(args[0].length());
}
Suppose I have this:
/**
* Single-word method.
*/
private void say(String word) {
System.out.println("Single word: " + word);
}
/**
* Multiple-word method.
*/
private void say(String... words) {
System.out.print("Multiple words: ");
for (String word : words) {
System.out.print(word);
}
System.out.println();
}
/**
* {#link #say(String...)}
*/
#SuppressWarnings("unused")
private void testJavadoc() {
}
public static void main(String[] args) {
say("hello");
say("world");
say("hello", "world");
}
If I run this, I get:
Single word: hello
Single word: world
Multiple words: helloworld
This proves that there is nothing wrong in defining a method with String and an overload with String....
When I mouse-over testJavadoc(), this is the Javadoc I see:
void testJavadoc()
#SuppressWarnings(value={"unused"})
say(String)
Clicking on say(String) brings me to the Javadoc for the first method without vararg.
If I remove say(String) method, then the Javadoc works fine.
I'm using eclipse neon 3 (4.6.3). Is this supposed to be the correct behavior?
This looks like it might be a bug in Eclipse, as you are correct in that it should reference the vararg method (I don't have Eclipse so I am unable to test).
Testing in IntelliJ, I can see the expected reference.
More-so, if you go ahead and actually generate the JavaDoc, you should be able to see the correct output.
I was wondering how I could check args.length within a method.
For example:
public static void commandLineCheck (int first, int second){
if (args.length==0){
//do something with first and second
}
}
public static void main(String[] args) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
commandLineCheck(first, second);
}
I get a "cannot find symbol: args" error when I do this. Right now, I'm thinking I need to pass args[] through the method as well. I've tried this but it then gives me an "" error. Is there a beginner-friendly solution to this?
EDIT: Thank you so much for the quick response guys! It worked!
Change your code like this (You need to pass the array's parameter to your check method)
public static void commandLineCheck (int first, int second, String[] args){
if (args.length==0){
//do something with first and second
}
}
public static void main(String[] args) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
commandLineCheck(first, second, args);
}
And it will work. However the following test (args.length==0)does not make much sense since you have already assumed that args.length is greater or equal to 2 by extracting two values from it inside the main method. Therefore when you get to your commandLineCheck method, this test will always be false.
You need to pass the String [] args to your commandLineCheck method. This is written the same way as you declare the array for your main method.
public static void commandLineCheck (String[] args){
if (args.length==0){
//do something with first and second
}
}
Also you probably want to change your main method and commandLineCheck method a bit.
public static void commandLineCheck(String [] args) {
/* make sure there are arguments, check that length >= 2*/
if (args.length >= 2){
//do something with first and second
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
}
}
public static void main(String[] args) {
commandLineCheck(args);
}
I'm trying to take input by using code int rs=Integer.parseInt(args[0]); but it throw exception ArrayOutOfBondException. Please help me code is below.I need to take input only one time in commandline argument
package techgig;
import java.util.*;
public class Techgig {
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
public static void main(String[] args) {
Vector v = new Vector();
// TODO code application logic here
System.out.println("Amount Mark has:");
System.out.println("=============================");//here is the code
int rs=Integer.parseInt(args[0]);
// int rs=50;
System.out.print("===============================");
//int a=0;
int count=0;
int min=0,temp,totalamount=0;
System.out.print("\nToys Available:{");
for(int a=0;a<ta.length;a++)
{
if(a!=0)
{
System.out.print(",");
}
System.out.print(ta[a]);
}
System.out.print("}\n");
System.out.println("Buy Maximum toys with maximum left");
for(int i=0;i<ta.length;i++)
{
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[j]<ta[i])
{
temp=ta[j];
ta[j]=ta[i];
ta[i]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
for(int k=0;k<ta.length;k++)
{
totalamount=min;
// System.out.print("\t"+ ta[k]);
min=min+ta[k];
if(min >rs)
{
break;
}
count=count+1;
v.add(ta[k]);
}
int sav=0;
sav=rs-totalamount;
//System.out.println("Amount Mark has:"+rs);
System.out.println("Output:{"+v.size()+","+sav+"}");
System.out.println("Explanation");
System.out.println("Maximum number of toys="+v.size()+""+v);
System.out.println("Saving="+sav);
}
}
You need to pass command line arguments while running java program.
If you don't pass any command line arguments then args will be empty array, that is with length 0. And accessing 0th element from empty array will throw ArrayIndexOutOfBoundsException.
If you want to use args[0] you need to pass command line arguments to the program. If you're running your program from an IDE, you will get the exception that you get.
Let the name of the class having your main method is MyClass.java Then you must run your program from command line like
java MyClass 12
Where 12 is the command line argument which you are passing to your program(you may try with different argument)
Note: When you will not pass any argument but access the args in your program then you will see this exception originating
I made a class Anagrams that writes the permutations of the words in a sentence and when I run the compiled program as java Anagrams "sentence1" "sentence2"... It should generate the permutations of each of the sentences. How would I get it to do that?
import java.io.*;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Anagrams
{
...
public static void main(String args[])
{
String phrase1 = "";
System.out.println("Enter a sentence.");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try { phrase1 = input.readLine(); }
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println();
new Anagrams(phrase1).printPerms();
}
}
this is what i have so far i just need it to run on "sentence1" "sentence2" ...
when i type the command java Anagrams "sentece1" "sentence2" ...
ive already compiled it using javac Anagrams.java
From your comment I think your only question is how to use command line arguments to solve the task:
Your main method is looking like this:
public static void main(String args[])
but should look like this
public static void main(String[] args)
You see that there is an array of strings that holds the command line arguments. So if your executing your code with
java Anagrams sentence1 sentence2
Then the array has the length 2. In the first place (args[0]) there is the value sentence1 and in the second place (args[1]) there is the value sentence2.
An example code that prints all your command line arguments looks like this:
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
Now you should be able to use your anagram algorithm for each command line argument.
Here's a simple example of getting the arguments from the command line.
Bear in mind that this is open to "IndexOutOfBoundsException"s if you don't provide enough arguments, so make sure to check that in your code!
class ArgsExample {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]);
}
}
C:\Documents and Settings\glow\My Documents>javac ArgsExample.java
C:\Documents and Settings\glow\My Documents>java ArgsExample "This is one" "This
is two"
This is one
This is two
C:\Documents and Settings\glow\My Documents>
Varargs would allow you to use an indeterminate number of strings in a method signature, if that's what you're looking for. Otherwise, Roflcoptr is right if it's a question of passing arguments into main.