Reputation: 107
In a JAVA 'char[] a' , I want to replace all the charachters by 'q', except 'x' and 'y'. I tried it by the JAVA code below. It works but fails to replace the last character. I need help to complete the replacement.
public static void main( String[] args )
{
char[] a ={'x','y','z','x','y','r','b'};
for(int i=0; i<a.length; i++){
if ( a[i]=='x') {
i=i+1;
if ( a[i]=='y') {
i=i+1;
a[i]='q';
}
System.out.println(a);
}
}
}
Upvotes: 1
Views: 943
Reputation: 1757
You need to check whether the current char (at index i
) is not x
or y
. If it is one of there characters the for loop continues as usual and checks the next character.
for(int i = 0; i < a.length; i++){
char c = a[i]; //get current char
if(c != 'x' && c != 'y'){ //check if it is a x or y
a[i] = 'q' //replace current char
}
}
Upvotes: 0
Reputation: 1
surely instead of:
if (a[i] == 'x'){i=i+1;
if (a[i] == 'y'){i=i+1;
a[i] = 'q';
}
System.out.println(a);
}
you can do:
if (a[i] != 'x' || a[i] != 'y'){
a[i] = q;
System.out.println(a);
}
Upvotes: 0
Reputation: 10061
As Jens points out, don't ever modify the loop counter. Java doesn't care about this, but you may. Assuming we're in the first iteration, therefore:
int i = 0;
if ( a[i]=='x') { // i is still 0
i=i+1; // i becomes 1
if ( a[i]=='y') { // OOPS, i is 1 here. so this is a[1] and therefore 'y'
i=i+1;
a[i]='q';
}
System.out.println(a);
}
In a for
loop, you can use continue;
to skip the rest of the loop and jump to the next iteration.
Remember that the exit condition of a for
gets only evaluated once: at the beginning of the for
block.
Upvotes: 0
Reputation: 57306
Your code inside the loop will only replace by q
any char that follows sequence x, y
. One way to replace all chars except x
and y
is can change your loop to:
for(int i=0; i<a.length; i++){
if ( a[i]!='x' && a[i] != 'y') {
a[i]='q';
}
}
System.out.println(a);
Also note that your System.out.println
is seemingly in a wrong place and will not output anything useful.
Upvotes: 0
Reputation: 1349
I'm not going to inspect your code, but i will show you a way how u can accomplish your goal.
char[] a = {'x', 'y', 'z', 'x', 'y', 'r', 'b'};
for (int i = 0; i < a.length; i++) {
if (a[i] == 'x' || a[i] == 'y') {
continue;
} else {
a[i] = 'q';
}
}
System.out.println(a);
The keyword continue in java skips actual iteration and goes to the next one.
Upvotes: 1
Reputation: 9427
replace everything within your for by:
if ( a[i] != 'x' && a[i] != 'y' ){ a[i] = 'q'; }
Upvotes: 3