Array of integers as command line argument along with other commands - java

So for my JAVA program the user has to give 6 arguments using the command line or Linux environment. One of these 6 commands is a list of numbers which I have them in the program as array of integers.
I'm not quite familiar with how it would be able to read in the list of numbers as the 6th argument ? Wouldn't the computer think of it as several arguments and not multiple numbers for one argument ?
Any help would be appreciated:)

That's correct, Java will interpret multiple spaced arguments as each their own, and put each separately into the String[] args arguments for your main. However, you can still handle this by specifying that the last argument must be a list of numbers. Doing this, you can simply loop after the 5th argument, and be confident that everything you're getting should be a part of the list.
public static void main(String[] args) {
// handle first 5 args
for (int i = 5; i < args.length; ++i) {
// everything accessed by args[i] at this point is a part of your list
}
}
You can then specify input via the java command
java -jar MyApp.jar arg1 arg2 arg3 arg4 arg5 int1 int2 int3 int4 int5 int6
# int1 to int6 will be read by the loop

Related

Generating millions of random integers to give as input to a Java program

I've wrote some sorting algorithms in Java, and verified their correctness for small inputs. Now, I wanted to check how they fare against each other as the number of elements that need sorting reach up to millions.
So I was looking for something along the steps:
Run the sorting algorithm
Ask the number of elements user wants to sort (I'd likely input > 1 million)
Give the input of entered size through random integer generation.
I was wondering how the 3rd step could be achieved, w/o having to rewrite the sorting algorithms themselves. I'm using LINUX terminal to run my code.
Thanks!
There is a fairly simple way chain together the output of a linux script to the input of a java program. The following approach should work for you
echo N | ./createInput.sh | java -cp "/srcpath/" packagePath/YourInputToAlgorithm
Where:
N is the number of elements to sort
createInput.sh is the linux number generator (must accept $1 as number of elements)
YourInputToAlgorithm is the java code which uses a Scanner to read values then executes your sorting algorithm on the input
Here are very simple implementations to illustrate the approach:
Linux generator:
#!/bin/bash
# Read the number of elements
read NUMBER_ELEMENTS
# Must echo it to Java program
echo $NUMBER_ELEMENTS
# This implementation just creates number 1..NUMBER_ELEMENTS in reverse order
until [ $NUMBER_ELEMENTS-lt 1 ]; do
echo $NUMBER_ELEMENTS
let NUMBER_ELEMENTS-=1
done
Java Code:
public class ReadStdIn {
public static void main(String[] args) {
List<Integer> input = new ArrayList<Integer>();
Scanner s = new Scanner(System.in);
int numberElements = s.nextInt();
while (numberElements > 0) {
input.add(s.nextInt());
numberElements--;
}
s.close();
Collections.sort(input); // Here you would call your algorithm
System.out.println(input);
}
}
An example:
echo 5 | ./createInput.sh | java -cp "/src/" stackoverflow/ReadStdIn
Creates the output as expected:
[1, 2, 3, 4, 5]

Can you pass an ArrayList as a command line argument for a java program

I am attempting to pass as input to a java program via a command line argument an ArrayList of BigIntegers.
I understand calling a program as such:
java myProgram one two
args[0] = "one"
args[1] = "two"
But if I was to run the program as such
java myProgram arrayList
How would I convert the String[] representation of this Arraylist back to an ArrayList<BigInteger>
The arrayList will be returned from a separate java file that returns an arrayList of BigInetegr, could I use that java program as an input to this one?
I am a little confused as how I would go about this.
Thanks!
As long as you are passing actual decimal strings to your program, e.g. java myProgram 123 456.
List<BigInteger> bigInts = new ArrayList<>(args.length);
for(int i = 0; i < args.length; i++)
bigInts.add(new BigInteger(args[i]));
Or using Java 8 streams:
List<BigInteger> bigInts = Arrays.stream(args)
.map(BigInteger::new)
.collect(Collectors.toList());
But if you're passing words to your program, then two things, you will need a custom function to parse English words to BigInteger, plus I doubt anyone will be typing out an integer large enough require a BigInteger.

How can I overcome ArrayIndexOutOfBoundException for Integer.parseInt(args[0])? [duplicate]

This question already has answers here:
String[] args parameter: java.lang.ArrayIndexOutOfBoundsException
(3 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I've seen below code in one of the video tutorial.There its executes fine but while I'm trying to execute in my system, it is compiling fine but I'm getting runtime error saying,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
class Test13
{
public static void main(String[] args)
{
int i = Integer.parseInt(args[0]);
System.out.println(i);
}
}
Can someone please guide me what's wrong with this code and how to rectify?
Thanks in advance!
It looks you're not passing in any parameters when you run your code.
From the Java doc for ArrayIndexOutOfBoundsException: 'Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.'
Therefore you're trying to pull a value from the args array with an index 0, but the array is less than this size (in this case it's empty).
In order for this to prevent an exception being thrown you can apply a size check around the statement.
if(args.length>0) {
int i = Integer.parseInt(args[0]);
System.out.println(i);
}
if (args.length > 0) {
Integer.parseInt(args[0])
}
ArrayIndexOutOfBoundsException occurs when you try to access an element at an index which does not exist in the array.
For example: suppose int a[]={2,4,5,10,3} is an array.
the size of array is 5 and index starts from 0.
Which means your array ranges from index 0 to index 4 where element at index 0 is the first element i.e. 2 and element at index 4 is the last element i.e. 3
if you try to access any elements at an index which is not in the range 0 to 4 it will show you ArrayIndexOutOfBoundsException because no such index exists in the array.
Now in your case args is command line argument which means you have to pass parameters when you run your code.
If you are running your code from terminal then after java yourclassname you have to pass parameters.
For example: java yourclassname 10 20 30
here 10 20 30 are your command line arguments which get stored in your args array and args[0]=10 args[1]=20 args[2]=30
If you haven't passed any arguments during running your code your args is empty and therefore you will get ArrayIndexOutOfBoundsException
hope it helps you to understand the concept of command line arguments.
You should pass an argument to your main method when executing your application.
For example, in command line type:
java Test13 123
Then the output should be:
123
Moreover you can check argument availability by check args.length, like what Adam said in prev answer.
You are not passing any argument while running your program. If you are running from command line then write java Test13 1. you will be able to get your result in output.
If you are using eclipse to run your program then provide your arguments in "Run Configuration" ->Arguments tab -> Program Arguments text box -> give value as 1.
You will be able to run your program
This is a runtime error as you might have observed the compilation goes smoothly. Now, why this happens is because you have to pass the "argument" while you give the run command (as in 2)
1. You might have run this command, without actually passing the argument [0]:
When you do this, the array is of length 0 as there are no arguments passed to the main function. Which is how the program is expected to run according to your code.
$ java Test13
This will give an error output. The one you got, with Array exception.
2. Try running this command, that is, type a number along with your command:
$ java Test13 727
Here, you are passing the argument [0] as 727 to the main function. Which adds the element to your array. This should work fine.
Similarly, suppose you have more arguments like [0], [1] and [2] And, you forget to add numbers after '727' like in command 2. You must get a similar error. Unless you do this (giving three inputs for your command):
$ java Test13 727 837 9
This means you need to give your input during the run command itself. However, in C++ with 'cin' in your code, you can give input after running the first command. Java is safer this way, although no real threat exists here.
Hope this works for you :)

understanding this task 'Summing'

I'm having a lot of trouble understanding what this assignment is asking me to do. I'm an absolute beginner, a few weeks of learning Java/programming in general, and this is very hard for me. So apologies for not being very specific in the title.
I'd really appreciate it if someone could explain to me, perhaps with a bit of sample code for one example (I'm not asking people to do the task for me, I just find it easier to understand that way) so I can get the idea of what to do.
Thank you.
Specification of Summing:
This programs takes input from the command line.
The first input is K, an integer, followed by an arbitrary number a_1, ..., a_N of floating-point numbers.
If K=0, then N is output.
If K > 0, then the a_i are grouped in groups of size K, inside the groups the numbers are multiplied, and all the products are added, yielding the output.
If K < 0, then the summation sums up the reciprocal values of the products.
In the special case K=1 the output thus is a_1 + ... + a_N.
In the case K=-1 the output is 1/a_1 + ... + 1/a_N.
There are two error cases:
If no command-line argument is given, then error-code 1 is to be returned.
If K < 0, and one of a_i = 0, then error-code 2 is to be returned.
In both cases there must be no output.
The return-code of a program is set via System.exit(code);
Note that the return-code of a program is obtained on the command line via echo $?.
There must never be any other output. Also no additional spaces or line breaks are allowed.
Here are the examples for the case of no errors: http://pastebin.com/F2uz262v
You will find the command line arguments here:
public static void main(String args[]) {
// ^ these are the command line arguments
So to get K,
int K = Integer.parseInt(args[0]);
but actually that's not how you should write it, because this is Java and Java variables should start with a lower case letter.
int k = Integer.parseInt(args[0]);
First let's deal with the case where k=0. We have to test if k is 0:
if(k == 0) {
and if it is, then N is the number of additional arguments, which is
int numberOfAdditionalArguments = args.length - 1;
and then we print it (with no line breaks afterwards, like it says!)
System.out.print(numberOfAdditionalArguments);
then we close the } block
}
I think that's enough to get you started.

Input In Java- How does it work?

Hey guys, with a lot of help from you i was managed to write this nice code (I'm new in it, so kind of exciting.. :) )
And still I have not understand how can I input this code.
first of all, I get an this error in the console line (I'm using Eclipse):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at NumberConverter.main(NumberConverter.java:5).
What does that mean?
I just want to chack whether it works, and I can't call the function/program any how.
I used to call in an "old fashion way", like in scheme, to the function that I wrote and see if something happens. How does it work in java? Do we call the program itself? function? what and where do we write? -I want to chack if it works, doesn't matter how, and I'll be glad to know how can I plugin input.
Thank you so much!
public class NumberConverter{
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
toOctal(i);
toHex(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
public static void toOctal(int int1){
System.out.println(int1 + " in octal is");
System.out.println(Integer.toOctalString(int1));
}
public static void toHex(int int1){
System.out.println(int1 + " in hex is");
System.out.println(Integer.toHexString(int1));
}
}
It means there was an ArrayIndexOutOfBoundsException at line 5 of NumberConverter. This is most likely going to be this line (if the full source contains a package statement followed by a blank line, this will be line 5):
int i = Integer.parseInt(args[0]);
Which tries to access the first argument you passes to the program, since you did not pass any arguments to the program the arbs array is empty and attempts to access args[0] results in ArrayIndexOutOfBoundsException.
If you were running this from the command line you it should look something like this:
$ java com.mypackage.NumberConverter 1
Here $ is the prompt, com.mypackage is presumed to be the package name and 1 is the command line argument which you will be able to access via args[0]`.
Since you are using eclipse and not via a command line here is a nice blog post on adding command line arguments from within eclipse.
you have to set arguments for app start up. You can do this in Run Configuration editor (Right click on project -> Run as.. -> Run Configurations). In Arguments tab you can put one to program Arguments field. One argument per line (eg. 5).
The ArrayIndexOutOfBoundsException occurs because of empty args array that you want to take first element of empty array - args[0]. You can't do this because the array is empty if no app start up arguments are set.
ArrayIndexOutOfBoundsExceptions means (from JavaDoc):
Thrown to indicate that an array has
been accessed with an illegal index.
The index is either negative or
greater than or equal to the size of
the array.
From your exception, args[0] throws ArrayIndexOutOfBoundsExceptions because 0 is greater than or equal to args.length. My suggestion is to find out what arguments is the OS returning to your JVM which is then passed to your app and see if args[0] is initialized and populated.
Also, running a program from Eclipse requires you to set arguments through Run Configurations.
an ArrayIndexOutOfBoundsException is thrown when you try to access an index outside of an array. Let's say that I have an array of size 2. I can access the first and second elements using the indices 0 and 1 respectively, but if I try to access the element in index 4, an exception is thrown:
public static void stam() {
int[] array = { 0, 1 };
// this will print 0
System.out.println(array[0]);
// this will print 1
System.out.println(array[1]);
// this will crash the program
System.out.println(array[4]);
}
Your instinct was correct that you can easily test your program using input, although using a literal value and a variable are probably an easier, and certainly more flexible option. In any case, you can set up the run configuration to include command line arguments via the Run > Run Configurations... window.
As you probably guessed, the reason why your program was crashing is because you try to access the first command line argument in line 5 of your class, but the argument wasn't there, so the array has 0 elements.
A slightly more flexible way of running a java program with command line arguments is by calling the main method of a different class, and manually passing it a String array. But if you want to test your methods quickly, just pass them literal values.

Categories

Resources