[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2011-10-04
25
Medium Priority
?
319 Views
Last Modified: 2012-06-27
Hi,
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?


0
Comment
Question by:Tolgar
  • 9
  • 9
  • 7
25 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 36913802
Both target variables are of type String?
0
 

Author Comment

by:Tolgar
ID: 36913828
yes...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36913861
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++) {	
	    sb.append(sep).append(args[i].toString());
	    sep = "\n";
	}
	return sb.toString();
    }

Open in new window

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 47

Expert Comment

by:for_yan
ID: 36913899

It is better to use
System.getProperty("line.separator");
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

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36913937
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
0
 

Author Comment

by:Tolgar
ID: 36920141
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++) {	
	    		    sb.append(sep).append(args[4][i].toString());
	    		    linesep = "\n";
	    		}

Open in new window


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

Thanks,
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36920175
So you mean that args[3] is just int
and args[4] is array ?

That seesm strange
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36920187
And waht is args[0], args[1] ?

What if you first try to prtint:

for (Object a : args){
System.out.println(a);

}

and let's see what will be the output
0
 

Author Comment

by:Tolgar
ID: 36920330
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?

Thanks,
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36920547
You just need to nest the loops - or apply the one loop to args[4]
0
 

Author Comment

by:Tolgar
ID: 36920601
Sorry but can you please show me how to do with the exact syntax?

 I am kind of new to java.

Thanks,
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36920676
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

0
 

Author Comment

by:Tolgar
ID: 36920704
@CEHJ
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?


Thanks,
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36921065

Print your args in this way:
for (Object a : args){
System.out.println(a);

}

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


0
 

Author Comment

by:Tolgar
ID: 36921436
by the way, everthing that I pass to java is string.
0
 

Author Comment

by:Tolgar
ID: 36921446
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

Thanks
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36921463

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?
0
 

Author Comment

by:Tolgar
ID: 36921482
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.

Thanks,
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36921488
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;

try{
i = Integer.parseInt(numRec);

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

String [] recs = new String[i];

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

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


}

Open in new window

:


0
 

Author Comment

by:Tolgar
ID: 36921500
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



Thanks,
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36921531
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",
    "$Login",
    ($#Rec + 1),
    "@Rec",
    "$ID",
    "$clstr', 
    ... (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){
System.out.println(s);
}

and it will facilitiate our understanding quite a llot







0
 
LVL 47

Accepted Solution

by:
for_yan earned 1000 total points
ID: 36921634

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",
    "$Login",
    ($#Rec + 1),
    "@Rec",
    "$ID",
    "$clstr',
    ... (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













0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36921655
>>1- How do you know that args[4] is separated by commas?

Because you said didn't you - possibly in your other q?
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 1000 total points
ID: 36921751
I'm pretty sure this is quite like what you want. It works fine for me:
//========================= PERL =====================
#!/usr/bin/perl

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

system(
    qw(
      java
      -jar myTools.jar
      ),
    @files
);
//====================================================

//========================= 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

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36921766
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
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month19 days, 18 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question