0

Declare array m of integer values and create it (allocate memory). The size of the array should be defined by the parameter provided in the command line during program execution.

public class A {
    public static void main(String[] args) {

        int[] a;
        int[] b = new int[n];
        for (int i = 0; i < n; i++) {
            b[i] = a[i];
        }
    }
}

This is my code but I think it's incorrect. Should I use a variable args in my code? And please explain me more about memory allocation. Thank you.

Banana
  • 2,435
  • 7
  • 34
  • 60
  • 1
    You should use the `String[] args` parameter of `main()` to access any command line parameters. Read up about what those `args` mean. – JimmyB Feb 13 '18 at 08:46
  • 1
    Your code is also incorrect for two more reasons: You don't initialize `a[]`, so you will get a `NullPointerException` at `b[i] = a[i]`; as you will see, the variable `n` is not declared anywhere, so that will give you a compile error. – JimmyB Feb 13 '18 at 08:48
  • Ok, I will solve those mistakes. But should I use for loop for doing this task? – Zhdanovas Valerka Feb 13 '18 at 08:53
  • about the memory alocation- there are two terms to know- declaration and definition... when you wrote `int[] a` then it is just declared but not defined , so you cannot access eg. to `a[0]`- you will got nullpointer, to avoid this you have to definite it- eg. `int[] a = new int[5]` then you will got allocated array sized of 5 items (default value for int is 0, so they should be initialized to zeros), but if you will the same with the String eg. all items will be null (but can access to item). And dont forget indexing is usually from zero- so `a[0]` is first and `a[4]` last item in array – xxxvodnikxxx Feb 13 '18 at 10:16
  • 1
    if you are learning java, I recommend you use some book. – mightyWOZ Feb 13 '18 at 10:27

4 Answers4

1

1) you need initialize a[]

2) use String[] args to retrieve command line argument (and you need to parse it to Integer )

Try like this .

class A {
  public static void main(String[] args) {
    try {
      String nn = args[0];
      int n = Integer.parseInt(nn);

      int[] a = new int[n];
      for (int i = 0; i < n; i++) {
        // your implementation goes here
      }
    }
    catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Please specify a argument");
    }
    catch (NumberFormatException e) {
      System.out.println("Argument must be a integer value");
    }
  }
}
Akila
  • 1,258
  • 2
  • 16
  • 25
1

Yes, you should use variable args in your code.

Parse String args to number:

int firstArg;
if (args.length > 0) {
    try {
        firstArg = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[0] + " must be an integer.");
        System.exit(1);
    }
}

Refer: https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

Exception_al
  • 1,049
  • 1
  • 11
  • 21
Maniche
  • 19
  • 5
1

You indeed need to use the args variable. Parameters you pass to the Java program are stored into the args variable by the JVM, making them available for the programmer.

I assume one parameter (the intended array size) is passed to the program, and that will be args[0].

You need to parse this String as an int, and use that number as array size:

// We assume args[0] exists and can be parsed as an integer, or else a
// NumberFormatException will be thrown
int size = Integer.valueOf(args[0]);

// We can use the size variable as array size.
int[] m = new int[size];

Now the array m has a size of the number given through the command line. Notice that the array size is not known at compile time, only at runtime. An array cannot be resized once created. Its length can be retrieved using m.length. Its values are initialized to 0.

If you want to print each element of the array, you can use

  • a for loop:

    for (int i = 0; i < m.length; i++) { // Loop variables are often called i
        // System.out.println prints its argument to the console
        System.out.println(m[i]);
    }
    
  • or an enhanced for loop (also known as a foreach loop):

    for (int n : m) {
        System.out.pritnln(n);
    }
    
  • or using Java Streams:

    either

    Arrays.stream(m).forEach(System.out::println);
    

    or

    IntStream.of(m).forEach(System.out::println);
    

More about memory allocation:

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
0

It's not clear, whether you need Scanner on Inputstream or something similar, or whether you can use the args:

The size of the array should be defined by the parameter provided in the command line during program execution.

"Parameter" sounds much like args, but they are provided ahead of program execution, not during.

But during program execution, I wouldn't call it a parameter, but an input.

Since you don't need any imports, using args is less complex.

user unknown
  • 35,537
  • 11
  • 75
  • 121