How to loop through an input array and assign each element to another array

I have a perl code and I pass some variables to a java code. Some of these variables are arrays.

In the java code I want to pass these inputs (the ones that are arrays) to a variable in Java.

In order to do that, I pass the length of the array along with the array as a second variable to my java code.

Now, in Java I need to write a loop to go through this input array and assign each of its element to the variable in java by appending new line character between each of them.

Here is the sudo code:
 java.lang.Integer fileLength = args[3];
 //loop through args[4] for args[3] times and assign each value to fileList and append a new line //character at the end of each one
java.lang.String[] fileList = args[4]{i}+"\n";

Open in new window

In one case the variables are integers and the others are strings.

Can you please let me know how I can write it in Java for both cases?

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Both target variables are of type String?
TolgarAuthor Commented:
I would be inclined to something like the following:
public static String formatVariable(Object[] args, int length) {
	StringBuilder sb = new StringBuilder();
	String sep = "";
	for(int i = 0;i < args.length;i++) {	
	    sep = "\n";
	return sb.toString();

Open in new window

OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.


It is better to use
that should work on all OS

You probably may not need to use fileLength,
if your array was created correctly according to java
rules, but if it happens to have more elements that you actually need,
then better use fileLength, once they pass it to you.
This code should work for both Strings and int's

public  String getString() {
String linesep = System.getProperty("line.separator");
String s = "";
for(int j=0; j<fileLength; j++){
s += "" + args[j] + linesep;

return s;

Open in new window

It IS better to use ${line.separator} if you want platform portability. I was simply taking you literally with
Now, in Java I need to write a loop to go through this input array and assign each of its element to the variable in java by appending new line character between each of them

Don't use string concatenation though - oftentimes it will be inefficient
TolgarAuthor Commented:
I think in both of these answers, you loop through the args.

>>//loop through args[4] for args[3] times
But I want to loop within the args[4] in my case.

args[4] is an array that I pass from Perl. I don't know the syntax but it may be something like this:

	    	   java.lang.Integer fileLength = args[3];
	     	   java.lang.String linesep = "";
	    	   java.lang.StringBuilder sb = new StringBuilder();
	    		for(int i = 0; i<fileLength; i++) {	
	    		    linesep = "\n";

Open in new window

Because, if I loop through args then other args have other variables.

So you mean that args[3] is just int
and args[4] is array ?

That seesm strange
And waht is args[0], args[1] ?

What if you first try to prtint:

for (Object a : args){


and let's see what will be the output
TolgarAuthor Commented:
I have other stuff in args[0], args[1] and args [2].

They are all simple strings and I can easily assign them to a varaible in Java.

But the arrays part is tricky.

Do you have any idea?

You just need to nest the loops - or apply the one loop to args[4]
TolgarAuthor Commented:
Sorry but can you please show me how to do with the exact syntax?

 I am kind of new to java.

Assuming your args[4] is the csv variable you mention, then the below (See http:#36913861 )
String[] args4 = args[4].split(",");
String s = formatVariable(args4, args4.length);

Open in new window

TolgarAuthor Commented:
1- How do you know that args[4] is separated by commas?

2- Does this append a new line character between every element of the array?


Print your args in this way:
for (Object a : args){


we'll at klleast have minimu idea what we
are talking about

and then we'll go from there

Look, how CEHJ can know anything about arg[4] ?
He just guesses.

If you have the above printout, we'll at least have minimu information and maybe will know where to start

TolgarAuthor Commented:
by the way, everthing that I pass to java is string.
TolgarAuthor Commented:
ID: 27343614

and this is how I came to this point. Maybe it help a little bit. Because it is hard for me to print out the inputs after I pass them from Perl. The code must start with Perl


If everything which you get into java is String, then how you make array of arg[4] - is it indeed a comma separated list, which
can be parsed as CEHJ sugggested, or maybe there is some other separator? Do you have any idea?
TolgarAuthor Commented:
I mean all the variables that I pass into java are strings. Maybe it is unnecessary to say but I just wanted to mention it.

So all the args are strings. I think I am not mistaken. And It comes from here.

public static void main(java.lang.String args[])

Just an additional info.

Looking at that question I'm acually thinking that
args[0] is  Login;
args[1] is number of records (let's say n)
args[2], args[3],....up to args[1+n]  - these are your elements

and I actually even had posted a copde how to read rthem in java

public ststic void main(String [] args){
String login = args[0];
String numRec = args[1];

int i = -1;

i = Integer.parseInt(numRec);

}catch(Exception ex){
System.out.println("second argument should be int");

String [] recs = new String[i];

for(int j=0; j<recs.length; j++){

recs[j] = args[2+j];


Open in new window


TolgarAuthor Commented:
It is a comma separated list as you said:

 This is how I call my java code:
my @javaCmd = ('java', '-jar', "/Tool/myTool.jar", 
		$something1, $something2, @something3, $lengthsomething3, @something4, 
		$lengthsomething4, @something5,  $lengthsomething5, $something6, $something7, 
		$something8, $something9, $something10);

Open in new window

you cakll it this way but it is not a comma separated list it comes int java as array of args,
where args[0] corresponds to $something1
args[1] corresponds to $something2, etc.

But when you look at this:

my @javaCmd = ('java', '-jar', "$mydir/myTool/Tool-1.0.jar",
    ($#Rec + 1),
    ... (the rest)

Open in new window

then in that code as I uderstand PHP will feed one string for "$Login",
one string for   ($#Rec + 1), but it would replace
  "@Rec" with many strings, actually with  ($#Rec + 1) - this number of strings

So when they arrive in java program it happens as if java was called with this command line

java -jar JarName.jar login_name 100(or number of elements in the following array)   element1 element2 element3 ....

so each eleemnet of that array will get numbers
args[2], args[3], args[4], etc

So you eed just to crate in java another array , say myArray
and shoudl assign

myArray[0] = args[2];
myArray[1] = args[3];

that's waht my code above will be doing

I still don't understand why you don't want to print it from
the beginnig of main

liek that:

for(String s: args){

and it will facilitiate our understanding quite a llot


In normal situation, let's say you start java program manually with the command line, so you type the following line at the system prompt
with all items separated by spaces:

java -jar jarname.jar string_1 string_2 string_3 ...

so when you press "Enter" after that operations system reads this line invokes executable java.exe and feeds
the rest of the line to that executable

java.exe from these two items "-jar" and "jarname.jar" will figure out which java class in this jar to execute - and it will
load that class and invoke method main() of that class and then JVM (which is sysnonym to java.exe) will
provide method main() with array of arguments which programmer can use inside the main() method
So by that time java.exe will already remove -jar and jarname.jar from this line (as it thinks programmer does no need it)
and it will provide string_1 as args[0], string_2 as args[1], etc.

So when you issue this command in PHP:

my @javaCmd = ('java', '-jar', "$mydir/myTool/Tool-1.0.jar",
    ($#Rec + 1),
    ... (the rest)

PHP will form a string either like that:

java -jar jarmname.jar logiin number_of_records record1 recod2 record3 ...

or like that:

java -jar jarmname.jar logiin number_of_records record1,recod2,record3,...

and will feed this string to operating system like you do when you invokwe java manually form command line

If it forms the string with all spaces then your records will be in the
elements args[2],args[3], args[4], etc.
then you'll do

String [] myArray = new String[Integer.parseInt(args[1]);
and then
for(int j=0; j<myArray.length; j++)myArray[j] = args[j+2];

if it forms the string with commas the all your records will be in
args[2] and to get them

you'll need to split:

String [] myArray = args[2].split(",");

(we will need to hope that actual records do not contain commas inside, otherwise this split will be wrong).
in order to determine how we get these command line argumnents in the fiorst or second form
I was suggesting just to print all args in the beginning if main() method

Alternatively you can of course try each of these two variants and see which of them works

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
>>1- How do you know that args[4] is separated by commas?

Because you said didn't you - possibly in your other q?
I'm pretty sure this is quite like what you want. It works fine for me:
//========================= PERL =====================

my @files;
my $files_file = 'files.txt';
if ( -e $files_file ) {
    if ( open( $file_fh, '<', $files_file) ) {
        while ( my $file = readline($file_fh) ) {
            push @files, $file;
            print "Adding $file to files list\n";
        close $file_fh;
    else {
        print "Could not open $files_file: $!\n";

      -jar myTools.jar

//========================= JAVA =====================
public class MyTools {
    public static void main(String[] args) {
	for(String s : args) {
	    System.out.printf("Java will now read file %s\n", s);

Open in new window

yes, so those arguments come separated with white spaces, not commas,
the only thing is to move them to start from from  zero'th  elemnt of the array,
so the code in ID:36921488 should work and plce them in the array recs
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.