views:

45

answers:

2

Hi everyone,

i need some help and guidance in displaying the splitted Strings in order.

let say, i have username, password, nonceInString. i had successfully encrypted and decrypted those. then i split the decrypted data. it was done, too.

i want to display the decrypted data in order. something like this.

userneme: sebastian
password: harrypotter
nonce value: sdgvay1saq3qsd5vc6dger9wqktue2tz*

i tried the following code, but it didn't display like i wish to.
pls help. thanks a lot in advance.

String codeWord = username + ";" + password + ";" + nonceInString;
String encryptedData = aesEncryptDecrypt.encrypt(codeWord);
String decryptedData = aesEncryptDecrypt.decrypt(encryptedData);
String[] splits = decryptedData.split(";");
String[] variables = {"username", "password", "nonce value"};
for (String data : variables){
    for (String item : splits){
        System.out.println( data + ": "+ item);
    }
}
A: 

thats because your inner loop will loop through all the values in splits for each element in variables.

i assume you got something like

username ..
username .. 
username ..
password ..
pa....
Spyker
yes. it appear sort of like that. the answer by "polygenelubricants" works.
sebby_zml
+4  A: 

Your nested for-each logic is wrong; instead, you need to explicitly pair up the elements of the array by an index:

for (int i = 0; i < variables.length; i++) {
   System.out.println(variables[i] + ":" + splits[i]);
}

Note that this assumes that both arrays have the same lengths, and will throw an ArrayIndexOutBoundsException if the splits array is shorter than the variables array.


As a side note, for key-value mapping data structure, you may want to look at java.util.Map.

import java.util.*;

//...

Map<String,String> map = new HashMap<String,String>();
map.put("username", "sebastian");
map.put("password", "harrypotter");
System.out.println(map); // prints "{username=sebastian, password=harrypotter}"
System.out.println(map.get("password")); // prints "harrypotter"
polygenelubricants
I would do a test first: `if splits.length != variables.length throw Exception("Input format does not match expectations")` or something like that. I have the feeling that the data will, in the future, come from somewhere else:)
extraneon
@polygenelubricants: thanks a lot. it works.@extraneon: yeah, i might be doing so in future. thanks for your suggestion, as well.
sebby_zml