-3

I am trying to write a very simple program to receive input from the user and print it out again on the screen. But I'm getting an error.

My code:-

import java.util.*;

class res_cmd {
    public static void main(String args[]){
        int first;
        System.out.println("Enter a number");
        first = Integer.parseInt(args[0]);
        System.out.println("The result is"+first);
    }
}

The error I'm getting:-

C:\Users\hp\Desktop>java res_cmd

Enter a number
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at res_cmd.main(res_cmd.java:7)

I am not sure why I'm getting this error. Scanner class and Buffer method are working but command line is not. Please help.

Emily
  • 1,030
  • 1
  • 12
  • 20
  • 1
    the `args` passed into the `main` method are command line arguments, so if you did `java res_cmd 52` it would work. If you want iteractive user input try using a `Scanner` – Scary Wombat Oct 29 '19 at 07:11
  • Provide the arguments. like java res_cmd arg1 arg2 . refer this https://www.javatpoint.com/command-line-argument – Lova Chittumuri Oct 29 '19 at 07:12
  • The fact that you print "Enter a number" shows you don't understand how the command line params work. If you want to print that text before entering a number, you'll need to use an instance of Scanner. – Stultuske Oct 29 '19 at 07:15

2 Answers2

1

You have not passed any value to main method from command line. To execute java application from command line with input parameter you need do as below

java <main class> <input parameter>

e.g. java res_cmd 20

Ajeet
  • 68
  • 1
  • 9
0

java res_cmd should be having a parameter passed in same command as below:

java res_cmd 20

20 is your parameter here

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86