Calculate length of first argument in java - java

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());
}

Related

pass array through method (java command line arguments)

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);
}

How to take single input in java

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

Getting java args into a Arraylist wont work

i´m almost freaking out because of the following problem:
public class FileMate {
public static void main(String[] args) {
Walker walker = new Walker();
int mode = Integer.parseInt(args[0]);
Checker.mode = mode;
List<String> drives = new ArrayList<String>();
for (int i=1; i == args.length; i++) {
drives.add(args[i]+":\\");
}
for (String path : drives) {
walker.walk(path);
}
}
}
The first argument is an integer and gets succesfully assigned to "mode".
But the part where the drive letters should be assigned to the list "drives" getting skipped at runtime.
I already debugged it step by step and the args array contains the mode and the 2 drive letters.
The for loop condition must be true for the loop to run, not for it to stop. Change your condition to:
i < args.length
Incidentally, you may want to check the length of the args array before you start accessing it, just in case the user didn't provide any arguments.

Print argument from Console

i'm tring to run argument from ubuntu console.
./myTool -h
and all i get is only the print of "1".
someone can help please ?
thanks !
public static void main(String[] argv) throws Exception
{
System.out.println("1");
for(int i=0;i<argv.length;i++)
{
if (argv.equals("-h"))
{
System.out.println("-ip target ip address\n");
System.out.println("-t time interval between each scan in milliseconds\n");
System.out.println("-p protocol type [UDP/TCP/ICMP]\n");
System.out.println("-type scan type [full,stealth,fin,ack]\n");
System.out.println("-b bannerGrabber status\n");
}
}
argv is an entire array. What you are trying to match, is the entire content of the array with the string -h. Try doing this:
public static void main(String[] argv) throws Exception
{
System.out.println("1");
for(int i=0;i<argv.length;i++)
{
if (argv[i].equals("-h"))
{
System.out.println("-ip target ip address\n");
System.out.println("-t time interval between each scan in milliseconds\n");
System.out.println("-p protocol type [UDP/TCP/ICMP]\n");
System.out.println("-type scan type [full,stealth,fin,ack]\n");
System.out.println("-b bannerGrabber status\n");
}
}
}
Side Note: This previous SO post might also be worth going through.
You miss the array index in the if condition:
argv[i].equals("-h")
You are comparing an array with a string. Change it to:
if (argv[i].equals("-h"))
You try to compare String[] with String.
Try instead:
if (argv[i].equals("-h"))

Command-Line Arguments in NetBeans

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");
}
}
}

Categories