Reputation: 57
I am trying to print every second letter in the string but for some reason I only print the first second letter correctly but after that it keeps printing in a weird order. Here is my code:
out.print("Please enter a word: ");
String word = in.nextLine();
char[] c = word.toCharArray();
int x = 0;
while (x < c.length) {
if (c[x] % 2 != 0) {
out.print(word.charAt(x) + " ");
}
x++;
}
Upvotes: 1
Views: 225
Reputation: 6226
You should change this:
if (c[x] % 2 != 0) {
to
if (x % 2 != 0) {
This compares the index you are working with instead of comparing the character. x
is the position of the character. c[x]
is the character. You can read c[x]
as "the value at position x
in array c
".
Upvotes: 6
Reputation: 1926
Problem area: You are checking value instead of index
while (x < c.length) {
if (c[x] % 2 != 0) {
out.print(word.charAt(x) + " ");
}
Convert it to: Checking index instead of value
while (x < c.length) {
if (x % 2 != 0) {
out.print(word.charAt(x) + " ");
}
Upvotes: 0
Reputation: 298103
You are calculating the character modulo 2 instead of the index modulo 2
By the way:
String word …
for(int ix=1; ix<word.length(); ix+=2)
out.print(word.charAt(ix) + " ");
makes it far simpler.
Upvotes: 1
Reputation: 178243
Why are you attempting to determine if the character (c[x]
) is odd? You should be testing the index itself.
if (x % 2 != 0) {
Upvotes: 1