-1

I used an if statement to give the user a custom error message when args.length == 0. However, when no argument is passed, instead of printing my custom message I get an out of bound error.

String w1 = args[0];
int n1 = Integer.parseInt(args[1]);
  for(int x = 0; x < n1; x++) {
    System.out.println(w1);
  }

String w2 = args[2];
int n2 = Integer.parseInt(args[3]);
  for(int b = 0; b < n2; b++){
    System.out.println(w2);
  }

String w3 = args[4];
int n3 = Integer.parseInt(args[5]);
  for(int c = 0; c < n3; c++) {
    System.out.println(w3);
  }

  if(args.length == 0){
    System.out.println("Error: No user input.");
    return;
  }

  }
Matt
  • 3
  • 4

2 Answers2

0

Revised after code was shown.

Java: Check if command line arguments are null

I recommend always checking if ((args == null) || (args.length == 0)), or if ((args != null) && (args.length > 0)) depending on your need.

if((args == null) || (args.length == 0))
{
  System.out.println("Error: No user input.");
  return;
}

if (args.length == 1) {
  String w1 = args[0];
  int n1 = Integer.parseInt(args[1]);
  for(int x = 0; x < n1; x++) {
    System.out.println(w1);
  }
}

if (args.length == 3) {
  String w2 = args[2];
  int n2 = Integer.parseInt(args[3]);
  for(int b = 0; b < n2; b++){
    System.out.println(w2);
  }
}

if (args.length == 5) {
  String w3 = args[4];
  int n3 = Integer.parseInt(args[5]);
  for(int c = 0; c < n3; c++) {
    System.out.println(w3);
  }
}
 
Community
  • 1
  • 1
Enkode
  • 4,515
  • 4
  • 35
  • 50
0

Your code:

if(args.length == 0){
    System.out.println("Error: No user input.");
    return;
}

Should be at the beginning, because when there are no elements in args[] and you access them like this:

String w1 = args[0];
int n1 = Integer.parseInt(args[1]);
  for(int x = 0; x < n1; x++) {
    System.out.println(w1);
}

You get the ArrayIndexOutOfBoundsExeption. Simply put the check for args.length() == 0 should be at the beginning

thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23