This line of java code is not working: int d = (value2 - kValue) % 26 ; it is supposed to give the value for (value2 - kValue) mod 26, but it *sometimes* giving a false value; for example with the case of: int d = (4 - 19) % 26 = -15 <----false, according to my ti.89 (and google) the correct value is 11. I know there is an error I'm making somewhere, but I can't find it. What am I doing wrong?
what I do when I have java code giving me weird numbers is to break apart all the steps and system out the results after each step. that always helped me isolate my problems.
public class test { public static void main(String[]args) { int d = (-15) % 26; System.out.println(d); } } jmathew3, I don't see how to break the problem down further than above. The output is -15. However, if I google (4-19)mod 26, I get 11. 11 happens to work for the program I'm working on, it is the same result I get from my ti.89. It is the result I need. Does anyone know how I can write (-15)mod26 in java so that I get the correct answer, 11? Thanks.
The reasons this is happening is because of how modulus is calculated in Java. Java uses the formula: x % y = x - (y * (x/y)) PHP: For your Example: int d = 15 - (26 * (15/26)); int d = 15 - (26 * 0); //Integer Division[1] int d = 15 - (0); int d = 15; PHP: This site explains it in more detail, check out the honing your skills section (http://mindprod.com/jgloss/modulus.html) You would probably need to write your own modulus equation if x is larger than y. [1] http://www.cs.umd.edu/~clin/MoreJava/Intro/expr-int-div.html
it is because modulus on negative numbers is different than on positive numbers for example -15 % 26 you have to go to the next multiple that is less than -15 which is -26, then you subtract -26 and -15 and get |-11| = 11
Not in Java. In Java the sign of the first number is taken. It does not matter if you do 15 % 26, you will also get 15, because of the reason I gave. http://mindprod.com/jgloss/modulus.html
That is good. It can be a fun language. Java has a lot of good qualities as well as some not so good ones. Again, this also doesn't matter. The reason the OP is getting an unexpected result is due to how modulus is calculated in Java. Try doing it in your compiler.