问题描述:

This should put word yup to every second character, yap to every fifth and both yup yap to every tenth. It does put only yup to every second character.

I can't figure out what's the problem. Thank you for your help.

for(int i = 0; i < word.length(); i++) {

if( i % 2 != 0) {

System.out.print(word.charAt(i) + " yup");

System.out.println();

}

else if( i + 1 % 5 == 0) {

System.out.print(word.charAt(i) + " yap");

System.out.println();

}

else if( i + 1 % 10 == 0) {

System.out.print(word.charAt(i) + " yup yap");

System.out.println();

}

else{

System.out.println(word.charAt(i));

}

}

}

网友答案:

Put () in your else if operations. Mod (%) has precedence over sum, that's why it's not working.

else if( (i + 1) % 5  == 0)

and

else if(( i + 1) % 10 == 0) 
网友答案:

Modulo 5 "hides" modulo "10", must rethink Your algorithm. Allways a number is multiplicity of 10, is 5 too

网友答案:

Reverse the if-else statements and put i + 1 in braces:

    if((i + 1) % 10 == 0)   {
        System.out.print(word.charAt(i) + " yup yup");
        System.out.println();
    }
    else if((i + 1) % 5 == 0)    {
        System.out.print(word.charAt(i) + " yap");
        System.out.println();
    }
    else if(i % 2 != 0)   {
        System.out.print(word.charAt(i) + " yup");
        System.out.println();
    }
    else{
        System.out.println(word.charAt(i));
    }

If (i + 1) % 10 is zero, then (i + 1) % 5 is zero, too.

相关阅读:
Top