Kenneth Faried
Kenneth Faried

Reputation: 57

Characters Array

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

Answers (4)

Kara
Kara

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

Prateek
Prateek

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

Holger
Holger

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

rgettman
rgettman

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

Related Questions