I've tried many hours to solve array task, but it seems to me that I'm stuck. The task is to create a program that prints the number of given command line parameters and lists them.
You gave 2 command line parameters.
Below are the given parameters:
1. parameter: 3455
2. parameter: John_Smith
My program starts from wrong index + I'm not sure about the given task. How does the program know how many parameters to use if that hasn't been initialized? Or am I just completely lost with the exercise?
This is what I've done:
import java.util.Scanner;
public class ex_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
int param = reader.nextInt();
String[] matrix = new String[param];
for (int i = 0; i < matrix.length; i++) {
matrix[i] = reader.nextLine();// This is the part where my loop fails
}
System.out.println("You gave " + matrix.length
+ " command line parameters.\nBelow are the given parameters:");
for (int i = 0; i < matrix.length; i++) {
System.out.println(i + 1 + " parameter: " + matrix[i]);
}
}
}
And my own output:
3 //This is the number of how many parameters the user wants to input
2 // Where is the third one?
omg //
You gave 3 command line parameters.
Below are the given parameters:
1 parameter:
2 parameter: 2
3 parameter: omg
EDIT:
I DID IT! I DID IT!! After more Googling I found this:
if (args.length == 0) {
System.out.println("no arguments were given.");
} else {
for (String a : args) {
}
}
Then I just modified the program and Voilà the program compiled. Here is the whole program:
import java.util.Scanner;
public class Echo {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no arguments were given.");
} else {
for (String a : args) {
}
}
System.out.println("You gave " + args.length
+ " command line parameters.\nBelow are the given parameters:");
for (int i = 0; i < args.length; i++) {
System.out.println(i + 1 + ". parameter: " + args[i]);
}
}
}
I want to thank everyone who answered to this, the help was really needed! :)