Reputation: 45
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! :)
Upvotes: 1
Views: 126
Reputation: 34321
I think you've confused what command line parameter means. A command line parameter is a parameter passed to the main
method when the program runs, while System.in
is capturing user input at the command line as the program runs.
The command line parameters are passed to the main
method in the args
parameter, so for example:
java MyClass one two three
Would pass the array ["one", "two", "three"]
as the args
parameter to the main
method.
All you have to do then is use the args
array to print the data information you require.
Upvotes: 2
Reputation: 17007
Command line arguments are not text read by the program with Scanner
and the like, they are strings specified in the args
array that is an argument to main. It seems like you need to output the contents of that array instead of reading input and outputting it.
Upvotes: 2