简体   繁体   中英

Java for loop prob

I have two Strings,A and B, A has the value of "ABCDE" and B the value of "12345" and I would like to make a for loop that makes the String C, to have the value of "A1B2C3D4E5" , the problem is that the value of A and B may vary, A and B can be equal or A greater than B just by one character, only these two options are possible:

if(A.length()>B.length()){
   B=B+"_";
}
int length=A.length()+B.length();
for(int count = 0; count == length;count++){
   C=C+A.charAt(count)+B.charAt(count);
}
System.out.println(C);

But nothing prints out.

just try like this

    for(int count = 0; count < length/2;count++){
       C=C+A.charAt(count)+B.charAt(count);
    }

Your problem is your conditional in the for loop, "count == length". This would mean the for loop runs so long as count is equal to length, ie it will not run unless the length is 0 (the initial condition of count).

You could write:

if (A.length() > B.length()) B += "_";
for (int i = 0; i < A.length(); i++) C = C + A.charAt(i) + B.charAt(i);
System.out.println(C);
int max = B.length()
if (A.length() > B.length()){
    max = A.length()
}
String C = "";
for (int i = 0; i < max; i++){
    if (i < A.length){
        C = C + A.charAt(i)
    }
    if (i < B.length){
        C = C + B.charAt(i);
    }
}

This checks to get the maximum length to iterate, and then in the for loop, only adds characters that exist, in an alternating pattern from each string until one string is empty, and then the rest of the other string is appended to the end one character at a time. This allows for this method of concatenation on two strings of any length, not just strings with lengths that differ by 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM